perlwww-mechanize

How can I recover from a timeout with Perl's WWW::Mechanize?


I'm using WWW::Mechanize 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?


Solution

  • 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.