Search code examples
rexceptionvariable-assignmentrcurl

Assigning a value in exception handling in R


 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


Solution

  • 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.