gpt4 book ai didi

perl - 无法捕获 DBI 错误

转载 作者:行者123 更新时间:2023-12-01 00:09:23 27 4
gpt4 key购买 nike

我正在编写一个 Perl 脚本,但似乎无法捕获 DBI 错误,无论我如何尝试。我试过这个:

use DBI;

$db = DBI->connect("dbi:ODBC:Driver={SQL Server};Server=localhost;DATABASE=nodepoint;UID=sa;PWD=test;") or print "Something happened.";

还有这个:

use DBI;

eval
{
$db = DBI->connect("dbi:ODBC:Driver={SQL Server};Server=localhost;DATABASE=nodepoint;UID=sa;PWD=test;");
};
if ($@) { print "Something happened."; }

两者都未能捕捉到错误,而是我在屏幕上看到了这个:

DBI connect('Driver={SQL Server};Server=localhost;DATABASE=nodepoint;UID=sa;PWD=test','',...) failed: [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (SQL-08001) [state was 08001 now 01000]
[Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (SQL-01000) at C:\dev\test.pl line 5.

这是一个大问题,因为在 IIS 上使用时,它会在发现错误时抛出 500.2 Bad Gateway。我需要捕获它以便显示正确的消息。

最佳答案

默认的错误处理是:

RaiseError => 0
PrintError => 1
PrintWarn => 0

您想将 PrintError => 0 传递给 connect


如果您更喜欢检查错误:

my $dbh = DBI->connect($dsn, $user, $passwd, {
RaiseError => 0,
PrintError => 0,
});

if (!$dbh) {
die($DBI::errstr);
}

如果您希望抛出异常:

my $dbh = eval {
DBI->connect($dsn, $user, $passwd, {
RaiseError => 1,
PrintError => 0,
})
};

if (!$dbh) {
die($@);
}

关于perl - 无法捕获 DBI 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27259174/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com