R避免 "restarting interrupted promise evaluation"警告

标签 r error-handling try-catch

问题

似乎在一个函数中,当您评估多次产生错误的表达式时,您会收到警告重新启动中断的 promise 评估。例如:

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
}

但是,我收到大量重新启动中断的 promise 评估消息:

>   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 的真正警告。

最佳答案

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

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

关于R避免 "restarting interrupted promise evaluation"警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20596902/

相关文章:

R-将不等长的字符数组转换为数据帧

ios - 在异步 block 中使用xcode 7.0 beta处理错误

java - 尝试提示用户从 catch block 重新输入,但 catch block 终止?

r - 使用 tryCatch 和 source

r - 如何修复 tm 包以奇怪的顺序加载大量文档的问题?

r - rmarkdown 中的增量嵌套列表

mysql - 通过 SSH 建立隧道后访问 R (RStudio) 中的 MySQL 数据库

vb.net - 无法解决的错误?

error-handling - jwt方法 `verify_expiration'错误

python - 在 Python 中使用 try-except-else 是一个好习惯吗?