Perl:强制堆栈跟踪“无法在未定义时调用方法”

我使用Perl和Catalyst作为Web框架.

如果在未定义的值…上抛出无法调用方法“XXX”的异常,我怎样才能全局强制执行堆栈跟踪?

假设您的Controller / Root.pm中有以下代码

use DateTime;

sub test  :Local :Args(0) {
    my ( $self, $c ) = @_;
    my $now = DateTime->now(time_zone=>'local');
    my $tmp = undef;

    my $throwing = $tmp - $now; #this will throw an exception!
    $c->res->body("OK");
}

打开http:// localhost:3000 / test抛出当然是异常:

Caught exception in MyApp::Controller::Root->test “Can’t call method
“subtract_datetime” on an undefined value at
/usr/local/lib/perl/5.10.1/DateTime.pm line 1619, line 1003.”

堆栈跟踪丢失了!

我怎样才能在这种情况下强制进行堆栈跟踪?

即我想得到(不是真正的输出,只能手工编写):

MyApp::Controller::Root::__ANON__('Can\'t call method "subtract_datetime" on an undefined value at /usr/local/lib/perl/5.10.1/DateTime.pm line 1619, <DATA> line 1003.^J') called at /home/user/MyApp/script/../lib/MyApp/Controller/Root.pm line 114
MyApp::Controller::Root::test('MyApp::Controller::Root=HASH(0x20583b60)', 'MyApp=HASH(0x206e9140)') called at /usr/local/share/perl/5.10.1/Catalyst/Action.pm line 65
Catalyst::Action::execute('Catalyst::Action=HASH(0x20668e88)', 'MyApp::Controller::Root=HASH(0x20583b60)', 'MyApp=HASH(0x206e9140)') called at /usr/local/share/perl/5.10.1/Catalyst.pm line 1687
eval {...} at /usr/local/share/perl/5.10.1/Catalyst.pm line 1687
Catalyst::execute('MyApp=HASH(0x206e9140)', 'MyApp::Controller::Root', 'Catalyst::Action=HASH(0x20668e88)') called at /usr/local/share/perl/5.10.1/Catalyst/Action.pm line 60
[ and the rest of the exception ...]

有了这个,我确切地知道异常是由Root.pm中的第114行引起的

最佳答案
我不确定它是否在Catalyst中有效,但通常可以通过包含CPAN模块Carp :: Always来强制执行堆栈跟踪,例如,通过在程序中的某处写入使用Carp :: Always;或者使用-MCarp :: Always开始启动perl脚本.

转载注明原文:Perl:强制堆栈跟踪“无法在未定义时调用方法” - 代码日志