views:

59

answers:

2

I'm using WWW::Nechanize to read a particular webpage in a loop that runs every few seconds. Occasionally, the 'GET' times out and the script stops running. How can I recover from one such timeout such that it continues the loop and tries the 'GET' the next time around?

+1  A: 

One option would be to implement a method to handle timeout errors and hook it into the mech object at construction time as the onerror handler. See Constructor and Startup in the docs.

You could even ignore errors by setting a null error handler, for example:

my $mech = WWW::Mechanize->new( onerror => undef );

but I wouldn't recommend that - you'll just get weird problems later.

martin clayton
+2  A: 

Use eval :

eval {
    my $resp = $mech->get($url);
    $resp->is_success or die $resp->status_line;
    # your code
};

if ($@) {
    print "Recovered from a GET error\n";    
}

The eval block will catch any error while GETing the page.

eugene y