Note that there are some explanatory texts on larger screens.

plurals
  1. POPerl: $SIG{__DIE__}, eval { } and stack trace
    text
    copied!<p>I have a piece of Perl code somewhat like the following (strongly simplified): There are some levels of nested subroutine calls (actually, methods), and some of the inner ones do their own exception handling:</p> <pre><code>sub outer { middle() } sub middle { eval { inner() }; if ( my $x = $@ ) { # caught exception if (ref $x eq 'ARRAY') { print "we can handle this ..."; } else { die $x; # rethrow } } } sub inner { die "OH NOES!" } </code></pre> <p>Now I want to change that code so that it does the following:</p> <ul> <li><p>print a full stack trace for every exception that "bubbles up" all the way to the outermost level (<code>sub outer</code>). Specifically, the stack trace should <strong>not</strong> stop at the first level of "<code>eval { }</code>".</p></li> <li><p>Not having to change the the implementation of any of the inner levels.</p></li> </ul> <p>Right now, the way I do this is to install a localized <code>__DIE__</code> handler inside the <code>outer</code> sub:</p> <pre><code>use Devel::StackTrace; sub outer { local $SIG{__DIE__} = sub { my $error = shift; my $trace = Devel::StackTrace-&gt;new; print "Error: $error\n", "Stack Trace:\n", $trace-&gt;as_string; }; middle(); } </code></pre> <p>[<strong>EDIT</strong>: I made a mistake, the code above actually <em>doesn't</em> work the way I want, it actually bypasses the exception handling of the <code>middle</code> sub. So I guess the question should really be: Is the behaviour I want even possible?]</p> <p><del>This works perfectly</del>, the only problem is that, if I understand the docs correctly, it relies on behaviour that is explicitly deprecated, namely the fact that <code>__DIE__</code> handlers are triggered even for "<code>die</code>"s inside of "<code>eval { }</code>"s, which they really shouldn't. Both <code>perlvar</code> and <code>perlsub</code> state that this behaviour might be removed in future versions of Perl.</p> <p>Is there another way I can achieve this without relying on deprecated behaviour, or is it save to rely on even if the docs say otherwise?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload