【问题标题】:R avoiding "restarting interrupted promise evaluation" warningR避免“重新启动中断的承诺评估”警告
【发布时间】:2014-01-03 00:23:28
【问题描述】:

问题

似乎在函数中,当您计算一个多次产生错误的表达式时,您会收到警告restarting interrupted promise evaluation。例如:

foo <- function() stop("Foo error")
bar <- function(x) {
    try(x)
    x
}
bar(foo())

产量

Error in foo() : Foo error
Error in foo() : Foo error
In addition: Warning message:
In bar(foo()) : restarting interrupted promise evaluation

如何避免这个警告并妥善处理?

背景

尤其是像写入数据库这样的操作,您可能会遇到需要您重试操作几次的锁定错误。因此,我创建了一个围绕 tryCatch 的包装器,它会重新评估一个表达式,直到成功为止 n 次:

tryAgain <- function(expr, n = 3) {
    success <- T
    for (i in 1:n) {
        res <- tryCatch(expr,
            error = function(e) {
                print(sprintf("Log error to file: %s", conditionMessage(e)))
                success <<- F
                e
            }
        )
        if (success) break
    }
    res
}

但是,我收到了大量 restarting interrupted promise evaluation 消息:

>   tryAgain(foo())
[1] "Log error to file: Foo error"
[1] "Log error to file: Foo error"
[1] "Log error to file: Foo error"
<simpleError in foo(): Foo error>
Warning messages:
1: In doTryCatch(return(expr), name, parentenv, handler) :
  restarting interrupted promise evaluation
2: In doTryCatch(return(expr), name, parentenv, handler) :
  restarting interrupted promise evaluation

理想情况下,我希望完全避免这些消息,而不是仅仅将它们屏蔽掉,因为我可能还想处理来自expr 的真正警告。

【问题讨论】:

    标签: r error-handling try-catch


    【解决方案1】:

    如果您希望显示每条错误消息,也可以不使用silent=TRUE 尝试此操作。在这两种情况下,您都不会收到有关 Promise 的消息:

    foo <- function() stop("Foo error")
    bar <- function(x) {
        try(eval.parent(substitute(x)), silent = TRUE)
        x
    }
    bar(foo())
    

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 2019-05-22
      • 2013-06-23
      • 1970-01-01
      相关资源
      最近更新 更多