traceback() for interactive and non-interactive R sessions
There is also the possibility to dump debugging information and load them later on. (See good ?debugger
help pages and comments on the topic)
via e.g.:
options(error = quote(dump.frames("testdump", TRUE)))
...
load("testdump.rda")
debugger(testdump)
or
options(error = quote({dump.frames(to.file = TRUE); q(status = 1)}))
BenBarnes's answer and dshepherd's comment are life saving. I will add one more parameter to avoid clogging up the screen in case one of the parameters is very big.
options(error=function(){traceback(2,max.lines=3);if(!interactive())quit("no",status=1,runLast=FALSE)})
With default values of its arguments, traceback()
will look for an object named .Traceback
in the baseenv()
for information on the call stack. It looks (from src/main/errors.c
) like .Traceback
is only created if, among other conditions, R_Interactive || haveHandler
, suggesting that this object is not created during non-interactive sessions. If there is no object named .Traceback
, you will get the message "No traceback available".
However, by passing a non-NULL value to the x
argument of traceback()
, one can obtain information about the call stack from a non-interactive session. With a non-zero integer value (indicating the number of calls to skip in the stack), c-level functions (R_GetTraceback
) are called to investigate the call stack instead of looking in .Traceback
.
So there are a couple ways to obtain traceback information in a non-interactive session:
f = function() {
on.exit(traceback(1))
1 + 'a'
}
f()
Or, setting options
as Brandon Bertelsen suggested
options(error=function()traceback(2))
The different values passed to x
in the two examples account for the different number of functions to skip
In the
on.exit
example,traceback(1)
skips the call totraceback()
.In the example setting
options
, there is an extra anonymous function that callstraceback()
which should/could also be skipped.
In the example in the OP, there's not much more information gained by using traceback()
compared to the automatic traceback provided in the case of an error in a non-interactive session. However, with functions that take (and are passed) arguments, using traceback()
will be much more informative than the standard presentation of the call stack in the non-interactive session.