in reply to handling WWW::Mechanize Error GETing

The typical way to tame 3rd party code in Perl is to wrap the "offending" call in eval and check $@ for the "exception"

my $temp; eval { $temp = $mech->get($imgsrc); } if ($@) { # alert the error }

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re^2: handling WWW::Mechanize Error GETing
by bh4017 (Initiate) on Dec 28, 2016 at 18:44 UTC
    Small (but essential) correction to jeffa's answer: The terminating semi-colon should be outside the eval braces otherwise perl throws a (unhelpful) compilation error. eval { $mech->get($imgsrc) }; if ($@) { # alert the error }

      Hi,

      Using if($@) is unreliable,

      The correct pattern is

      $temp = eval { $mech->get($imgsrc) }; if( not $temp ){ ... }

      But we're using mech so we dont need to store the response in $temp

      So even better

      eval { $mech->get( $imgsrc ); }; if( not $mech->res->is_success ){ ... }

      Or even better

      if( not eval { $mech->get( $imgsrc ); 1 } ){ ... }

      Or simply the generic version , it doesn't rely on $@

      eval { $mech->get( $imgsrc ); 1 } or do { ... };

      For explanation why using if($@) is unreliable see Devel::EvalError -- Reliably detect if and why eval() failed

        Hi,

        In general you are right about eval { ...; 1 } or do { ... } being better than eval { ... }; if ($@) { ... }, however note this

        eval { $mech->get( $imgsrc ); }; if( not $mech->res->is_success ){ ... }

        is quite different from all the other snippets of code so far: it only checks $mech->res->is_success, as opposed to all the other examples which would report any error inside an eval, so personally I'd recommend those other patterns over this particular example.

        Regards,
        -- Hauke D