Printing stack trace and continuing after error occurs in R

前端 未结 8 2058
再見小時候
再見小時候 2020-12-08 04:42

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

相关标签:
8条回答
  • 2020-12-08 05:33

    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.)

    0 讨论(0)
  • 2020-12-08 05:38

    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

    0 讨论(0)
提交回复
热议问题