Print stack trace when “Can't locate object method x via package y” (Perl)

杀马特。学长 韩版系。学妹 提交于 2020-02-04 07:25:52

问题


Chances are I invoke method x on an object of the wrong type, but it's way down in my call stack, so it's not obvious.

So: is there a way of always printing a full stack trace when this error occurs?


回答1:


To always print a full stack trace add use Carp::Always; or run the program with

perl -MCarp::Always script

or, with bash

PERL5OPT=-MCarp::Always script

what sets up the PERL5OPT environment variable and runs the (executable) script. For one, this allows the shebang (#!) line in the script to decide which interpreter is used. If you export it (say in the shell configuration file), export PERL5OPT=-MCarp::Always, then it will be used by all Perl scripts in that shell. Thanks to ikegami for comments.

To fine-tune which particular exceptions get more attention add the $SIG{__DIE__} hook

use Carp;

BEGIN { 
    $SIG{__DIE__} = sub { 
        confess @_ if $_[0] =~ /Can't locate object method/;  #'
    };  
};

and after the hook returns "... the exception processing continues as it would have in the absence of the hook, unless ...", see %SIG in perlvar. The code above dies normally on other errors.

Thus here you can change what happens as the die is thrown, with code run right before it goes. For example, see this post for how to get all lexicals for each frame in the call stack.

Messing with this can get tricky so please read up on it. See links in this post, for instance.




回答2:


The Carp module which ships with Perl can be used to generate stack traces.

Carp provide replacements for warn and die which can be used either to simply bump the offending file and line number 1 level back up the call stack or to produce a stack trace.

In your case it sounds like you're not actually calling die - that's happening as a result of attempting to call a non-existent method. For this circumstance you can use Carp's 'verbose' mode to force a stack trace globally. There are a number of ways to enable verbose mode. It can be done via the environment, from the command line used to invoke Perl or from inside your script:

use Carp 'verbose';


来源:https://stackoverflow.com/questions/45991133/print-stack-trace-when-cant-locate-object-method-x-via-package-y-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!