我可以在 Perl 中抑制来自 fetch.pm 的错误消息吗

Can i suppress error message from fetch.pm in Perl

当使用 Fetch 从 Teamcity 下载 url 时,出现 Fetch 失败!错误。但是文件的下载确实有效。

他们最近更改了我们 Teamcity 服务器的权限,因此我在获取要下载的文件的 URL 时必须使用用户名和密码。我只是想知道这是否会导致获取对网关的验证出现问题,但我可以下载文件。有没有办法抑制此错误或将其降级为警告?

Perl Code:
my $ff = File::Fetch->new(uri => "$uri"); 
my $where = $ff->fetch   ( to => "$DOWNLOAD_LOCATION" );
print Dumper($ff);

Output:    
Fetch failed! HTTP response: 502 Bad Gateway [502 notresolvable] at         
<path>\myfile.pl line 249.

Dumper Output:
$VAR1 = bless( {'vol' => '',
                'file_default' => 'file_default',
                '_error_msg' => 'Fetch failed! HTTP response: 502 Bad Gateway [502 notresolvable]',
                'file' => 'myfilename.zip',
                'scheme' => 'http',
                'path' => '/repository/download/buildlabel/1042086:id/',
                '_error_msg_long' => 'Fetch failed! HTTP response: 502 Bad    Gateway [502 notresolvable] at C:/Perl/lib/File/Fetch.pm line 598.

问题似乎是打印到 STDERR 的警告(消息)。显然你没有得到 die 否则程序将退出。您可以通过设置 $SIG{__WARN__} 挂钩来控制打印消息的过程,最好在一个块中本地化。

my $where;

FETCH: {

    local $SIG{__WARN__} = sub { 
        print "WARN: @_";        # or whatever appropriate
    };

    $where = $ff->fetch   ( to => "$DOWNLOAD_LOCATION" );    
};

my $where = do { 
    local $SIG{__WARN__} = sub { print "WARN: @_" };
    $ff->fetch;
};

信号的配置——打印到STDERR——在块外恢复,这是local提供的。请参阅 this in perlsub,特别是“Synopsis”之后的文本。您也可以在完成后说 $SIG{__WARN__} = 'DEFAULT'; 来手动执行此操作。

warn

No message is printed if there is a $SIG{__WARN__} handler installed. It is the handler's responsibility to deal with the message as it sees fit (like, for instance, converting it into a die).

另见 %SIG 条目 in perlvar

The routine indicated by $SIG{__WARN__} is called when a warning message is about to be printed. The warning message is passed as the first argument. The presence of a __WARN__ hook causes the ordinary printing of warnings to STDERR to be suppressed.


虽然决定调用什么 "error" 和调用什么 "warning" 可能有点武断,但很明显您的程序只向 STDERR 发出消息并继续。那么以上就够了。

如果您被 die 击中,那么您可以将代码包装在 eval.

正如the documentation所解释的那样,只需设置

$File::Fetch::WARN = 0;

抑制警告。