Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save traceback on error using tryCatch

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()
like image 512
Jeroen Ooms Avatar asked Mar 24 '23 17:03

Jeroen Ooms


1 Answers

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.

like image 118
Jeroen Ooms Avatar answered Apr 06 '23 02:04

Jeroen Ooms