Re: Trapping errors
"Francisco Zarabozo" <[email protected]> Fri, 10 Feb 2012 16:25:50 -0600
| Newsgroups | gmane.comp.lang.perl.active-perl |
|---|---|
| Message-ID | <[email protected]> |
Hi Barry,
> From: Barry Brevik
> Sent: Friday, February 10, 2012 4:05 PM
> Subject: Trapping errors
>
> I am writing a process that is going to run on a remote machine, and I
> want to log all of the errors.
>
> That is to say, in case my testing has been less than perfect, I want to
> log any error messages internally generated by Perl. I’ve got my own “die”
> messages covered; I mean the > actual Perl messages.
>
> Is there a signal or something that I can trap?
>
> Barry Brevik
You can eval your entire code of eval it by segments. This is an example
using a dummie log function called "logIt":
-------------------------------------------------------
use strict;
use warnings;
eval {
print "Hello world!\n";
print "Now I'm gonna die...\n";
die "This is a die call!";
};
print "This continues to run after the eval block even if there were
errors.\n";
print "End.\n";
# Here you can check for errors:
if (my $e = $@) {
logIt("We had errors: $e");
} else {
logIt("We had no errors.\n");
}
sub logIt {
my $m = shift;
print "LOG: ".localtime." - $m\n";
}
----------------------------------------------------------
...but that works for fatal errors only, not simple messages printed to
STDERR (like warnings). If you want to trap those too, you can do something
like the following example:
-----------------------------------------------------------
$| = 1; # Get STDERR messages in real time
use strict;
use warnings;
my $stderr = '';
eval {
# The following 2 lines will work only inside this block.
local *STDERR;
open *STDERR, '>>', \$stderr;
print "Hello world!\n";
print "Now I'm gonna warn you...\n";
warn "This is a warning call!";
print "Now I'm gonna die...\n";
die "This is a die call!";
};
warn "Here STDERR should work normally again, we left the localized scope.";
print "This continues to run after the eval block even if there were
errors.\n";
print "End.\n";
# Here you check for warnings:
if ($stderr) {
logIt("We had some warnings: $stderr");
}
# Here you can check for errors:
if (my $e = $@) {
logIt("We had errors: $e");
} else {
logIt("We had no errors.\n");
}
sub logIt {
my $m = shift;
print "LOG: ".localtime." - $m";
}
-----------------------------------------------------------------
HTH
Francisco Zarabozo
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs