我已经使用Perl绑定SVN::Client等编写了一些相当广泛的Perl模块和脚本。由于对SVN::Client的调用都深入模块,因此我覆盖了默认的错误处理。
到目前为止,我已经通过设置
$SVN::Error::handler = undef;
as described in the docs,但这使得单个调用有点混乱,因为您必须记住在列表上下文中调用SVN::Client
,并测试第一个值是否有错误。
我想切换到使用我要编写的错误处理程序;但是$SVN::Error::handler
是全局的,所以我看不到任何方法可以让我的回调确定错误来自哪里,以及在哪个对象中设置错误代码。
我想知道是否可以使用池来实现此目的:到目前为止,我忽略了与在Perl中工作无关的池,但是如果我使用自己创建的池调用SVN::Client
方法,是否会在同一个池中创建任何SVN::Error对象?
有没有人有这方面的知识或经验?
发布于 2010-05-17 07:21:56
好的,我假设问题是(a)当错误发生时,你想在某个对象中设置一个标志,然后在所有操作结束时检查标志,以及(b)你的错误处理程序(在全局变量中)需要某种方法来知道要接触哪个对象。您可以使用闭包来实现此目的,如下所示:
#
# This part is the library that implements error handling a bit like
# SVN::Client
#
sub default_error_handler {
croak "An error occurred: $_[0]";
}
our $global_error_handler = \&default_error_handler;
sub library_function_that_might_fail {
&$global_error_handler("Guess what - it failed!");
}
#
# This part is the function that wants to detect an error
#
sub do_lots_of_stuff {
my $error = undef; # No errors so far!
local($global_error_handler) = sub { $error = $_[0]; };
library_function_that_might_fail();
library_function_that_might_fail();
library_function_that_might_fail();
if ($error) {
print "There was an error: $error\n";
}
}
#
# Main program
#
do_lots_of_stuff();
关键是,在do_lots_of_stuff()
中,当我们将错误处理程序设置为匿名子时,该子将继续访问创建它的函数的局部变量-因此它可以修改$error
以发出错误发生的信号。
https://stackoverflow.com/questions/2639294
复制相似问题