rootcho has asked for the wisdom of the Perl Monks concerning the following question:

hi,
I want to capture all die's and instead of ending the script to write the error in file and continue.. In most of the palces I also use Carp to report errors, so i would want to capture them too..
Currently i'm tring this code

$SIG{__DIE__} = sub { print '>', @_, "<\n"};
then i simulate error and get this one :
>No such field 'USERx' at /usr/lib/perl5/site_perl/5.8.5/WWW/Mechanize +.pm line 1033 < No such field 'USERx' at /usr/lib/perl5/site_perl/5.8.5/WWW/Mechanize. +pm line 1033 >Trying to call non existing method at /home/myscript.pl line 0 <
In fact the error is generated in HTML::Form (with carp).
I have to get only the first error, but probably Carp and die handler are inter-winded in some way!!!
What is the right way to handle this...

Replies are listed 'Best First'.
Re: DIE handling ... carp!
by liverpole (Monsignor) on Jun 09, 2006 at 22:14 UTC
    Hi rootcho,

    Specifically, here's an example of a program trapping the "die", and continuing if desired. Note the eval which ambrus and cowboy mentioned, wrapping the entire while clause:

    use strict; use warnings; # Globals my $num = 1_000_000_000; # Signal handling $SIG{__DIE__} = sub { trap_otherwise_fatals() }; # Main program sure_to_fail(); print "Continuing anyway\n"; # ... more code here if desired ... # Subroutines sub trap_otherwise_fatals { print "** Would have died at num = $num **\n"; } sub sure_to_fail { eval { while (1) { my $log = log($num); printf "Log(%12d) = %10.6f\n", $num, $log; $num = $log; } } }

    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re: DIE handling ... carp!
by ambrus (Abbot) on Jun 09, 2006 at 21:16 UTC

    If you want to capture an error in such a way to continue execution, $SIG{__DIE__} won't work, you have to use eval{} instead.

Re: DIE handling ... carp!
by cowboy (Friar) on Jun 09, 2006 at 21:45 UTC

    Try using eval{} around the code that may die. You can even wrap your entire program in an eval if need be.

    I use this under mod perl to trap any 500 errors that may occur alerting the relevant people that something is wrong, as well as other eval's around code that may die, but if it does, I can deal with the error and continue.

Re: DIE handling ... carp!
by educated_foo (Vicar) on Jun 12, 2006 at 00:44 UTC
    Depending on what you mean by "continue", it might be best to locally override CORE::GLOBAL::die, like so:
    { my $realdie = \&CORE::GLOBAL::die; local *CORE::GLOBAL::die = sub { $realdie->(@_) if $something; print LOG @_ }; ## do_stuff }
    See the section on %SIG in perlvar for some discussion.