如何在Perl中捕获并重新抛出错误?
发布时间:2020-12-16 06:18:14 所属栏目:大数据 来源:网络整理
导读:假设我有一个模块Bar,它是模块Foo的子类包装器.我希望调用Bar的方法来模仿Foo – 甚至是致命的错误.到目前为止,很容易;我只是称之为SUPER方法. sub stuff { # Do stuff here SUPER::stuff(@_); # Do more stuff here} 但是,让我们说我想抓住,记录并重新抛出S
|
假设我有一个模块Bar,它是模块Foo的子类包装器.我希望调用Bar的方法来模仿Foo – 甚至是致命的错误.到目前为止,很容易;我只是称之为SUPER方法.
sub stuff {
# Do stuff here
SUPER::stuff(@_);
# Do more stuff here
}
但是,让我们说我想抓住,记录并重新抛出SUPER :: stuff()产生的任何致命错误.前两个步骤很简单: sub stuff {
# Do stuff here
eval {
SUPER::stuff(@_);
};
$@ and log("Naughty,naughty: $@");
# Do more stuff here
}
……但我不知道怎么做最后一部分.如何重新抛出错误,使得调用者无法区分对Foo-> stuff()的调用和对Bar-> stuff()的调用?我可以在日志语句之后插入$@并期望它做我想要的,或者这里有细微差别可能会让我遇到麻烦吗? 解决方法
在Perl中安全地eval / catch / log / rethrow的完整代码可能有点冗长.
sub stuff {
# Do stuff here
local $@; # don't reset $@ for our caller.
my $eval_ok = eval { # get the return from eval,it will be undef if the eval catches an error.
SUPER::stuff(@_);
1; # return 1 (true) if there are no errors caught.
};
if (!$eval_ok) { # don't trust $@ it might have been reset as the eval unrolled.
my $error = $@ || 'unknown error'; # copy $@ incase write_log resets $@,or is later changed to cause it to reset $@.
write_log("Naughty,naughty: $error");
die $error; # after all that we can rethrow our error.
}
# Do more stuff here
}
你可以使用暴徒的Try::Tiny sugested来简化: sub stuff {
# Do stuff here
try {
SUPER::stuff(@_);
} catch {
my $error = $_;
write_log("Naughty,naughty: $error");
die $error;
}
# Do more stuff here
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
