Search code examples
rloopstry-catchredo

How to redo tryCatch after error in for loop


I am trying to implement tryCatch in a for loop.

The loop is built to download data from a remote server. Sometimes the server no more responds (when the query is big).

I have implemented tryCatch in order to make the loop keeping.

I also have added a sys.sleep() pause if an error occurs in order to wait some minutes before sending next query to the remote server (it works).

The problem is that I don't figure out how to ask the loop to redo the query that failed and lead to a tryCatch error (and to sys.sleep()).

for(i in 1:1000){
    tmp <- tryCatch({download_data(list$tool[i])},
           error = function(e) {Sys.sleep(800)})
}

Could you give me some hints?


Solution

  • You can do something like this:

    for(i in 1:1000){
       
       download_finished <- FALSE
    
       while(!download_finished) {
    
        tmp <- tryCatch({
    
                 download_data(list$tool[i])
                 download_finished <- TRUE
    
               },
               error = function(e) {Sys.sleep(800)})
       }
    }