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

Hi everyone! I've got exception handling subsystem which converts dies to exceptions with stack trace using Exception::Class-like lib.
my $base_class = '...'; # base class for exceptions my $error_class = '...'; # my error class sub rethrow(;$) { my $e = @_ ? $_[0] : $@; die $e if blessed( $e ) && $e->isa( $base_class ); die $error_class->new( $e ); } sub try(&) { my $code = $_[0]; eval { local $SIG{__DIE__} = \&rethrow; &$code(); }; $@; }
And usage is:
my $e = try { # some code, potentially with errors };
Exception objects supports stringification. For most cases it works fine, but there is one case which breaks it. If I had module which dies duering loading and i'll try to require it with my try fucntion, $SIG{__DIE__} handler will be called twice. And second time it will be called with stringified exception from first time! So I lose call stack collected in first call and error location is lost. Is there any way to prevent such stringification?

Replies are listed 'Best First'.
Re: How to prevent exception stringification after error in require/use?
by thenaz (Beadle) on Aug 04, 2011 at 15:40 UTC

    Why not do:

    my $base_class = '...'; # base class for exceptions my $error_class = '...'; # my error class sub fixerror(;$) { my $e = @_ ? $_[0] : $@; return $e if blessed( $e ) && $e->isa( $base_class ); return $error_class->new( $e ); } sub try(&) { my $code = $_[0]; eval { &$code() }; $@ ? fixerror($@) : undef; }

    That way you don't have a callback that has the potential of getting called multiple times.

      I take it back. You use the $SIG{__DIE__} so that you can get the stack trace at the location the exception was thrown...