Search code examples
rfunctionerror-handlinggoogleway

Handling 500 internal server error in R geocoding function


I have written a function using the googleway package to geocode addresses, that unfortunately crashes when it encounters a 500 internal server error. The function is as follows:

rugeocoder.fun <- function(addr){
              require(googleway)
              output <- vector("list", length=length(addr))
              for(i in 1:length(addr)){
                  output[[i]] <- google_geocode(address=addr[i], key="myapikey", language="ru", simplify=T)
                  print(i)
                }
              return(output)
              }

(Yes, I know I could accomplish this using lapply instead of a loop inside a function, but I like having the counter print to the console.)

Naturally, this results in me losing all the output up to this point because of a relatively simple error. Is there something I can do to either have the function: a) save the output up to that point, so I can restart it at that address or b) keep trying until the server error disappears (I imagine a 500 error is likely to be temporary?).


Solution

  • Per the suggestions in the comments, I was able to keep the loop from crashing when it encounters an error with tryCatch():

    rugeocoder.fun <- function(addr){
                  require(googleway)
                  output <- vector("list", length=length(addr))
                  tryCatch({
                    for(i in 1:length(addr)){
                      output[[i]] <- google_geocode(address=addr[i], key="myapikey", language="ru", simplify=T)
                      print(i)
    
                    }},error=function(e) output[[i]] <- "Error: reattempt")
                  return(output)
                  }