在顶层调用错误?

Kar*_* W. 7 error-handling r

当我使用时tryCatch,我可以定义一个错误处理程序并用于conditionCall确定导致错误的调用.例如,

tryCatch(
    eval(parse(text="prnit('Hello')")),
    error=function(e) {
      cl <- conditionCall(e)
      #...
    })
Run Code Online (Sandbox Code Playgroud)

我可以在R提示符上找到错误的电话吗?到现在为止,我发现只有这个解决方案:

> err_hdl  <- function() {
    file1 <- tempfile("Rrawhist")
    savehistory(file1)
    rawhist <- readLines(file1)
    unlink(file1)

    cat("Error : ", tail(rawhist,1), "\n")
    return(TRUE)    
}
> options(error=err_hdl)
> prnit("Hello")
Run Code Online (Sandbox Code Playgroud)

但我相信必须有一个更直接的方式..

任何暗示赞赏!

我拿出一笔赏金.实现上述err_hdl函数行为而没有独立于平台的文件I/O 的第一个答案将被接受.

编辑 - 上面的代码似乎只适用于Windows.我正在寻找引发错误的输入.

Ben*_*nes 2

看起来dump.frames可以被告知不要转储到文件,而是转储到.GlobalEnv. 不过,除了 Mac 之外,我还没有在其他设备上测试过它。以下内容会有帮助吗?

err_hdl2 <- function() {
  dump.frames("theErr", to.file = FALSE)
  cat("What happened?\n", attr(theErr,"error.message"), "\nOh.\n")
}
options(error = err_hdl2)

> prnit(dt)
Error: could not find function "prnit"
What happened?
 Error: could not find function "prnit"

Oh.
Run Code Online (Sandbox Code Playgroud)

theErr我想,在全局环境中创建对象可能有一个缺点。

> theErr
$`function () 
{
    dump.frames("theErr", to.file = FALSE)
    cat("What`
<environment: 0x1030fe140>

attr(,"error.message")
[1] "Error: could not find function \"prnit\"\n"
attr(,"class")
[1] "dump.frames"
Run Code Online (Sandbox Code Playgroud)