使用 Try::Tiny 和 $_ 获取"the type of error"



我编写了以下方法来获取日志错误。我用$_来获取"错误类型"。

sub _log_warning {
    my $log = Log::Server->new(
        base_dir =>
          &config->current->{'log_reader'}->{'base_dir'},
        pattern => &config->current->{'log_reader'}->{'pattern'},
    );
    $log->infof("Could not register to DB. Got $_");
}

因为我看到$_用于获取产生的错误类型。我在这个上下文中使用了这个:

 use Try::Tiny;
 try { _log_to_database(); }
 catch {
     _log_warning();
 };

这在语法上可以吗?我期望_log_warning();要记录错误,$_应该说明发生的错误类型。但也许我没有用$_好吗?

更新:

当我试图产生一个错误,激活该方法时,我得到了:

 2013-07-04T11:15:56 [INFO] Could not register to DB. Got ã<81><9d>ã<81>®ã<82><88>ã<81>     <86>ã<81>ªã<83><95>ã<82>¡ã<82>¤ã<83>«ã<82><84>ã<83><87>ã<82>£ã<83>¬ã<82>¯ã<83><88>ã<83>>> ªã<81>¯ã<81><82>ã<82><8a>ã<81>¾ã<81><9b>ã<82><93>: /var/log/app.error.log.%Y%m%d at script.pl line 36.n at script.pl line 113

:(

@ikegami SOS

因此根据Try::Tiny文档:

在catch块中,捕获的错误存储在$_中,而以前的值$@仍然可以使用。

因此,此模块将$_设置为捕获的错误,因此您的使用看起来是正确的。这是一篇有趣的博客文章,讲述了设计背后的逻辑。

相关内容

最新更新