0

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?).

Sean Norton
  • 277
  • 1
  • 12
  • 2
    See `?try` and its similar functions for handling errors and conditions. – nicola Jun 10 '17 at 16:35
  • 1
    this is not actually an issue with `googleway` itself, is it? You can recreate the issue/requirement just with a simple `for-loop` example where you want to handle errors inside the loop - as per @nicola 's suggestion. – SymbolixAU Jun 11 '17 at 11:06
  • 1
    @SymbolixAU No, it's not, it's just an issue with Google - I've been playing around with tryCatch, and while I can get it to throw an error message and continue, I've yet to find a working way to get it to repeat that particular address until the 500 internal server error disappears. I suppose that's a new question. – Sean Norton Jun 11 '17 at 16:45
  • @SeanNorton - to repeat until a solution, you may want to consider a while loop. Just be sure to make it exit the loop eventually, even if you always get the 500-error. – SymbolixAU Jun 11 '17 at 23:21

1 Answers1

1

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)
              }
Sean Norton
  • 277
  • 1
  • 12