It turns out that the latest version of the evaluate
package has a function called try_capture_stack
which is a pretty good implementation of this.
Save traceback on error using tryCatch
-
30-05-2022 - |
Question
When calling an R function inside my webapp, I would like to catch the stack-trace when an error occurs and present it to the user for debugging purposes. Something like the output of traceback()
in an interactive session. However, traceback
doesn't seem to work when it is called inside the error handler, it returns No traceback available
:
f <- function() {
g <- function() stop("test traceback")
g()
}
errhandler <- function(e){
stacktrace <- traceback()
unlist(stacktrace);
}
out <- tryCatch(f(), error=errhandler)
Is there any way I can programatically catch the stack trace of an error? I.e. get the output that I would get when calling traceback()
manually after the error:
f()
traceback()
Solution
OTHER TIPS
The function tools:::.try_quietly
does something similar:
f <- function() {
g <- function() stop("test traceback")
g()
}
tools:::.try_quietly(f())
Error: test traceback
Call sequence:
3: stop("test traceback")
2: g()
1: f()
However, the errors and warnings are printed to outConn
using sink()
- this means you can't directly assign the results to an object. To work around this, you may have to change the code to use print()
instead of sink
(untried).
I did not get a stack as with traceback with try_capture_stack
, so I wrote a solution that works like try
, except that it also returns the call stack. tools:::.try_quietly
is neat, but does not save the stacks for later inspection...
tryStack <- function(
expr,
silent=FALSE
)
{
tryenv <- new.env()
out <- try(withCallingHandlers(expr, error=function(e)
{
stack <- sys.calls()
stack <- stack[-(2:7)]
stack <- head(stack, -2)
stack <- sapply(stack, deparse)
if(!silent && isTRUE(getOption("show.error.messages")))
cat("This is the error stack: ", stack, sep="\n")
assign("stackmsg", value=paste(stack,collapse="\n"), envir=tryenv)
}), silent=silent)
if(inherits(out, "try-error")) out[2] <- tryenv$stackmsg
out
}
lower <- function(a) a+10
upper <- function(b) {plot(b, main=b) ; lower(b) }
d <- tryStack(upper(4))
d <- tryStack(upper("4"))
cat(d[2])
More info in my answer here: https://stackoverflow.com/a/40899766/1587132