I've faced a similar issue before in https://stackoverflow.com/a/10318268/1331451.
What you need to do is add a $SIG{ALRM}
handler and use alarm
to call it. You set the alarm
before you do the call and cancel it directly afterwards. Then you can look at the HTTP::Result you get back.
The alarm will trigger the signal, and Perl will call the signal handler. In it, you can either do stuff directly and die
or just die
. The eval
is for the die
no to break the whole program. If the signal handler is called, the alarm
is reset automatically.
You could also add different die
messages to the handler and differentiate later on with $@
like @larsen said in his answer.
Here's an example:
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new;
my $res;
eval {
# custom timeout (strace shows EAGAIN)
# see https://stackoverflow.com/a/10318268/1331451
local $SIG{ALRM} = sub {
# This is where it dies
die "Timeout occured...";
}; # NB: \n required
alarm 10;
$res = $ua->request($req);
alarm 0;
};
if ($res && $res->is_success) {
# the result was a success
}
- perlipc for signals.