问题
似乎在一个函数中,当您评估多次产生错误的表达式时,您会收到警告重新启动中断的 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/