__DIE__ handlers and eval

drhyde on 2003-11-20T16:45:28

At work I'm writing a large application. It uses an in-house logging module. That installs, amongst other things, a __DIE__ handler so we can log errors with a stack trace and all sorts of other goodness before exiting.

The front-end is a CGI script which uses the Template Toolkit. Some templates mysteriously logged stuff and stopped, muttering about us not having some Apache::* module installed. We tracked this down to TT trying to use the module in an eval.

Dear module authors, if you're going to eval stuff because you expect it to die, be aware that __DIE__ handlers *are* called when stuff dies in an eval. Please temporarily remove the __DIE__ handler before doing your voodoo, and then restore it.

And just to prove it ...

perl -e '$SIG{__DIE__} = sub { print "Foo\n"; exit(1); }; eval "use Apache::NonExistent;"; print "Bar" if $@'


Check caller

gav on 2003-11-20T16:51:42

You just need to see if (caller(0))[3] eq '(eval)'. You'll get caught out by such things as HTML::Parser otherwise.

Re:Check caller

Juerd on 2003-11-20T18:42:31

I find using $^S much easier.
$SIG{__DIE__} = sub {
    return if $^S;
    ...;
};
See also perlvar.

Re:Check caller

drhyde on 2003-11-21T09:41:36

You are a wonderful person. May I have the pleasure of buying you beer some time?