trycatch R avoiding “restarting interrupted promise evaluation” warning



trycatch (1)

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.


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())




try-catch