R avoiding “restarting interrupted promise evaluat

2020-03-01 02:56发布

问题:

Problem

It seems that within a function, when you evaluate an expression that yields an error more than once, you get the warning restarting interrupted promise evaluation. For instance:

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

yields

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

How to avoid this warning and deal with it properly?

Background

Especially with operations like writing to a database, you might encounter locking errors that require you to retry your operation a few times. Hence I'm creating a wrapper around tryCatch that re-evaluates an expression up to n times until successful:

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
}

However, I'm getting loads of restarting interrupted promise evaluation messages:

>   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

Ideally I want to avoid these messages altogether rather than just muffle them, since I might also want to handle genuine warnings coming from expr.

回答1:

You can also try this without silent=TRUE if you want each error message to show. In neither case will you get the message about promises:

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