I\'m writing some R code that calls other code that may fail. If it does, I want to print a stack trace (to track down what went wrong), then carry on regardless. However, t
If something that triggers on option(error...) is of interest, you can also do this:
options(error=traceback)
From what I can tell, it does most of what Bob's suggested solution do, but has the advantage of being much shorter.
(Feel free to combine with keep.source=TRUE, warn=2, etc. as needed.)
I wrote a solution that works like try
, except that it also returns the call stack.
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