好像不打印“ Hello World”,但仍输出到stderr

问题描述 投票:0回答:1

我希望Perl或DBI在连接数据库时出错时不发送错误异常。我的目标是一旦我无法通过用户名/密码或URL问题连接到数据库,就无法将代码发送到监视服务器。

#!/usr/bin/perl -w
use strict;

use DBI;
use Data::Dumper;

my $dsn = 'DBI:ODBC:Driver={/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.5.so.2.1}';
my $host = 'whatever.com,1433';
my $database = 'xxxxx';
my $user = 'xxxxx';
my $auth = 'xxxxxxx';

eval {
my $dbh = DBI->connect("$dsn;Server=$host;Database=$database",
$user,
$auth);
};


if ($@) {
  print "Hello World.\n";
  ## Eventually, I'll put code here to send alerts to the monitoring server
}

即使使用eval,Perl / DBI仍会输出错误,并且不会打印“ Hello World”。

DBI connect('Driver={/opt/microsoft/msodbcsql17/lib64/libmsodbcsql- 
17.5.so.2.1};Server=xxxxx- 
xxxxxxx.com,1433;Database=xxxxxx','xxxxuser1',...) failed: [Microsoft][ODBC Driver 
17 for SQL Server][SQL Server]Login failed for user 'xxxxuser1'. (SQL-28000) at ./x.pl 
line 14.
perl dbi
1个回答
3
投票

默认情况下,DBI方法将错误消息打印到STDERR,并在错误时返回false。

要启用在错误时引发异常,请使用以下选项:

RaiseError => 1

要禁用打印到STDERR,请使用以下选项:

PrintError => 0

(这不会阻止未捕获的异常输出到STDERR。]

这是它的外观:

my $dbh = DBI->connect(
   "$dsn;Server=$host;Database=$database",
   $user, $auth,
   { PrintError => 0, RaiseError => 1 },
);
© www.soinside.com 2019 - 2024. All rights reserved.