7

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

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

我可以在 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")

但我相信一定有更直接的方法..

任何提示表示赞赏!

我发出了赏金。将接受第一个实现上述err_hdl功能的行为而没有平台独立的文件 I/O 的答案。

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

4

1 回答 1

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.

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"
于 2012-07-07T19:26:04.460 回答