eval 不打印 "Hello World" 并且仍然输出到 stderr
eval not printing "Hello World" and still outputs to stderr
我希望 Perl 或 DBI 在连接到数据库出错时不发送错误异常。我的 objective 是一旦我无法通过 username/password 或 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.
默认情况下,DBI 方法向 STDERR 打印一条错误消息,并在出错时 return false。
要启用错误抛出异常,请使用以下选项:
RaiseError => 1
要禁用打印到 STDERR,请使用以下选项:
PrintError => 0
(这不会阻止将未捕获的异常输出到 STDERR。)
这是它的样子:
my $dbh = DBI->connect(
"$dsn;Server=$host;Database=$database",
$user, $auth,
{ PrintError => 0, RaiseError => 1 },
);
我希望 Perl 或 DBI 在连接到数据库出错时不发送错误异常。我的 objective 是一旦我无法通过 username/password 或 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.
默认情况下,DBI 方法向 STDERR 打印一条错误消息,并在出错时 return false。
要启用错误抛出异常,请使用以下选项:
RaiseError => 1
要禁用打印到 STDERR,请使用以下选项:
PrintError => 0
(这不会阻止将未捕获的异常输出到 STDERR。)
这是它的样子:
my $dbh = DBI->connect(
"$dsn;Server=$host;Database=$database",
$user, $auth,
{ PrintError => 0, RaiseError => 1 },
);