Assigning a value in exception handling in R

2019-06-24 02:11发布

问题:

 while(bo!=10){
  x = tryCatch(getURLContent(Site, verbose = F, curl = handle),
            error = function(e) {
               cat("ERROR1: ", e$message, "\n")
               Sys.sleep(1)
               print("reconntecting...")
               bo <- bo+1
               print(bo)
               })
  print(bo)
  if(bo==0) bo=10 
}

I wanted to try reconnecting each second after the connection failed. But the new assignment of the bo value is not effective. How can i do that? Or if you know how to reconnect using RCurl options (I really didn't find a thing) it would be amazing.

Every help is appreciated

回答1:

The problem is the b0 scope of the assignment. However, I find try a little more friendly than tryCatch. This should work:

while(bo!=10){
    x = try(getURLContent(Site, verbose = F, curl = handle),silent=TRUE)
    if (class(x)=="try-error") {
           cat("ERROR1: ", x, "\n")
           Sys.sleep(1)
           print("reconnecting...")
           bo <- bo+1
           print(bo)
     } else {
           break
     } 
}

The above attempts 10 times to connect to the site. If any of this time succeeds, it exits.



回答2:

Create a variable outside the scope of tryCatch(), and update using <<-

bo <- 0
while(bo!=10){
    x = tryCatch(stop("failed"),
      error = function(e) {
          bo <<- bo + 1L
          message("bo: ", bo, " " conditionMessage(e))
    })
}

Or use the return value as a sentinel for success

x <- 1
while (is.numeric(x)) {
    x = tryCatch({
        stop("failed")
    }, error = function(e) {
        message("attempt: ", x, " ", conditionMessage(e))
        if (x > 10) stop("too many failures", call.=FALSE)
        x + 1
    })
}