How to retry a statement on error?

后端 未结 6 1272
慢半拍i
慢半拍i 2020-12-01 06:19

How can I simply tell R to retry a statement a few times if it errors? E.g. I was hoping to do something like:

tryCatch(dbGetQuery(...),           # Query da         


        
6条回答
  •  暖寄归人
    2020-12-01 06:42

    Here's a function to generate a custom condition to respond to

    locked <- function(message="occurred", ...) {
        cond <- simpleCondition(message, ...)
        class(cond) <- c("locked", class(cond))
        cond
    }
    

    and a function implemented to allow (an infinite number of) restarts

    f <- function() {
        cnt <- 0L
        repeat {
            again <- FALSE
            cnt <- cnt + 1L
            withRestarts({
                ## do work here, and if needed...
                signalCondition(locked())
            }, retry=function() {
                again <<- TRUE
            })
            if (!again) break
        }
        cnt
    }
    

    and the use of withCallingHandlers (to keep the context where the condition was signaled active unlike tryCatch) to handle the locked condition

    withCallingHandlers({
        n_tries <- 0L
        f()
    }, locked=function(e) {
        n_tries <<- n_tries + 1L
        if (n_retries < 3)
            invokeRestart("retry")
    })
    

提交回复
热议问题