Skip to content
Back to formatted view

Raw Message

Message-ID: <399CF5DD-4403-4460-8749-24DE126B66D0@bigelow.org>
Date: 2013-03-06T21:59:34Z
From: Ben Tupper
Subject: how to get xmlToList() to retry if http fails
In-Reply-To: <A632B3F93D861843A3C966F3962C3F840111393CF7D9@EMAIL05.pnl.gov>

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