R避免"重新启动中断的承诺评估"警告

mch*_*hen 30 error-handling r try-catch

问题

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

foo <- function() stop("Foo error")
bar <- function(x) {
    try(x)
    x
}
bar(foo())
Run Code Online (Sandbox Code Playgroud)

产量

Error in foo() : Foo error
Error in foo() : Foo error
In addition: Warning message:
In bar(foo()) : restarting interrupted promise evaluation
Run Code Online (Sandbox Code Playgroud)

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

背景

特别是对于写入数据库等操作,您可能会遇到锁定错误,需要您重试几次操作.因此,我正在创建一个包装器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
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到了很多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
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想完全避免这些消息,而不是仅仅消除它们,因为我可能还想处理来自的真正警告expr.

G. *_*eck 12

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

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