如何在tryCatch中显示错误位置?

TMS*_*TMS 6 exception-handling r try-catch

使用options(show.error.locations = TRUE)处理异常时,显示错误位置似乎不起作用tryCatch.我试图显示错误的位置,但我不知道如何:

options(show.error.locations = TRUE)

tryCatch({
    some_function(...)
}, error = function (e, f, g) {
    e <<- e
    cat("ERROR: ", e$message, "\nin ")
    print(e$call) 
})
Run Code Online (Sandbox Code Playgroud)

如果我然后查看变量e,那么位置似乎不存在:

> str(e)
List of 2
 $ message: chr "missing value where TRUE/FALSE needed"
 $ call   : language if (index_smooth == "INDEX") {     rescale <- 100/meanMSI[plotbaseyear] ...
 - attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
Run Code Online (Sandbox Code Playgroud)

如果我没有捕获错误,它将与源文件和行号一起打印在控制台上.如何使用tryCatch?

Wil*_*urg 0

您可以在错误处理程序中使用traceback()来显示调用堆栈。tryCatch 中的错误不会产生行号。另请参阅有关回溯的帮助。如果您防御性地使用 tryCatch 语句,这将帮助您缩小错误位置的范围。

这是一个工作示例:

## Example of Showing line-number in Try Catch

# set this variable to "error", "warning" or empty ('') to see the different scenarios
case <- "error"

result <- "init value"

tryCatch({

  if( case == "error") {
    stop( simpleError("Whoops:  error") )
  }

  if( case == "warning") {
    stop( simpleWarning("Whoops:  warning") )
  }

  result <- "My result"
},
warning = function (e) {
  print(sprintf("caught Warning: %s", e))
  traceback(1, max.lines = 1)
},
error = function(e) {
  print(sprintf("caught Error: %s", e))
  traceback(1, max.lines = 1)
},
finally = {
  print(sprintf("And the result is: %s", result))
})
Run Code Online (Sandbox Code Playgroud)