[R] how to get xmlToList() to retry if http fails
Ben Tupper
btupper at bigelow.org
Wed Mar 6 22:59:34 CET 2013
Hi,
On Mar 6, 2013, at 4:12 PM, Waichler, Scott R wrote:
> Hi,
>
> I am using xmlToList() in a loop with a call to a webservice, per the code below.
>
> # Loop thru target locs
> for(i in 1:num.target.locs) {
> url <- paste(sep="/", "http://www.earthtools.org/timezone", lat[i], lon[i])
> tmp <- xmlToList(url)
> df$time.offset[i] <- tmp$offset
> system("sleep 1") # wait 1 second per requirements of above web service
> } # end loop thru target locations
>
> Failure struck midway through my loop, with the message below.
>
> failed to load HTTP resource
> Error: 1: failed to load HTTP resource
>
You can wrap it in a try function as in the following (untested). I have made the thing stop if the second try fails, but you may want to do something more useful. Check out tryCatch, too.
for(i in 1:num.target.locs) {
url <- paste(sep="/", "http://www.earthtools.org/timezone", lat[i], lon[i])
tmp <- try(xmlToList(url))
if (inherits(tmp, "try-error")) {
Sys.sleep(2)
tmp <- try(xmlToList(url))
if (inherits(tmp, "try-error")) stop("Error fetching data")
}
df$time.offset[i] <- tmp$offset
system("sleep 1") # wait 1 second per requirements of above web service
} # end loop thru target locations
Cheers,
Ben
> I presume that the webservice failed to respond in this instance. How can I trap the error and have it retry after waiting a second or two, instead of exiting?
>
> Thanks. --Scott Waichler
> Pacific Northwest National Laboratory
> Richland, WA, USA
> scott.waichler at pnnl.gov
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org
More information about the R-help
mailing list