Subject: | Document how to use eval inside timeout... |
Date: | Thu, 21 Mar 2019 18:01:20 +0100 |
To: | bug-Time-Out [...] rt.cpan.org |
From: | Peter Valdemar Mørch <peter [...] morch.com> |
Lets say I have this existing code:
eval {
sleep 5;
die "bad\n";
};
if ($@) {
# Oh no, but an exception. Log it!
my $error = $@;
chomp $error;
printf "Got an error: %s\n", $error;
}
And I want to wrap it in a timeout. The naive approach that I would expect
to
work from the documentation would be:
use Time::Out qw(timeout);
timeout 1, sub {
eval {
sleep 5;
die "bad\n";
};
if ($@) {
# Oh no, but an exception. Log it!
my $error = $@;
chomp $error;
printf "Got an error: %s\n", $error;
}
};
if ($@) {
print "I got a timeout\n";
}
I would expect to see "I got a timeout". But that doesn't work. Instead I
get
this output:
Got an error: Time::Out::Exception=HASH(0x5569bd5152f0)
So if you're using Time::Out, any handling of $@ after an eval needs to let
"Time::Out::Exceptions "slip through" for the documented API of checking
for $@
after the timeout call to work. Like this:
use Time::Out qw(timeout);
timeout 1, sub {
eval {
sleep 5;
die "bad\n";
};
if ($@) {
if (blessed $@ && $@->isa('Time::Out::Exception')) {
# rethrow that Time::Out::Exception
die $@;
}
# Oh no, but an exception. Log it!
my $error = $@;
chomp $error;
printf "Got an error: %s\n", $error;
}
};
if ($@) {
print "I got a timeout\n";
}
Now I see "I got a timeout" as expected.
Or the $@ error handling just needs to handle the
if (blessed $@ && $@->isa('Time::Out::Exception')) {}
case.