我正在编写一个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
。我需要抓住它,这样才能显示正确的信息。
答案 0 :(得分:6)
默认错误处理是:
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($@);
}