How can I replace all 'die's with 'confess' in a Perl application?

后端 未结 4 1306
迷失自我
迷失自我 2021-02-02 13:56

I\'m working in a large Perl application and would like to get stack traces every time \'die\' is called. I\'m aware of the Carp module, but I would prefer not to search/replace

相关标签:
4条回答
  • 2021-02-02 14:41

    I usually only want to replace the dies in a bit of code, so I localize the __DIE__ handler:

     {
     use Carp;
     local $SIG{__DIE__} = \&Carp::confess;
    
     ....
     }
    

    As a development tool this can work, but some modules play tricks with this to get their features to work. Those features may break in odd ways when you override the handler they were expecting. It's not a good practice, but it happens sometimes.

    0 讨论(0)
  • 2021-02-02 14:42

    Use Devel::SimpleTrace or Carp::Always and they'll do what you're asking for without any hard work on your part. They have global effect, which means they can easily be added for just one run on the commandline using e.g. -MDevel::SimpleTrace.

    0 讨论(0)
  • 2021-02-02 14:43

    What about setting a __DIE__ signal handler? Something like

    $SIG{__DIE__} = sub { Carp::confess @_ };
    

    at the top of your script? See perlvar %SIG for more information.

    0 讨论(0)
  • 2021-02-02 14:49

    The Error module will convert all dies to Error::Simple objects, which contain a full stacktrace (the constructor parses the "at file... line.." text and creates a stack trace). You can use an arbitrary object (generally subclassed from Error::Simple) to handle errors with the $Error::ObjectifyCallback preference.

    This is especially handy if you commonly throw around exceptions of other types to signal other events, as then you just add a handler for Error::Simple (or whatever other class you are using for errors) and have it dump its stacktrace or perform specialized logging depending on the type of error.

    0 讨论(0)
提交回复
热议问题