无法捕获DBI错误

Den*_*ory 3 iis perl dbi sql-server-2008

我正在编写一个Perl脚本,无论我尝试什么,我似乎无法捕获DBI错误.我试过这个:

use DBI;

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

还有这个:

use DBI;

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

两者都无法捕获错误,而是在屏幕上显示:

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.
Run Code Online (Sandbox Code Playgroud)

这是一个很大的问题,因为在IIS上使用它会500.2 Bad Gateway在看到错误时抛出一个.我需要抓住它,这样我才能显示正确的信息.

ike*_*ami 6

默认错误处理是:

RaiseError => 0
PrintError => 1
PrintWarn  => 0
Run Code Online (Sandbox Code Playgroud)

你想传递PrintError => 0connect.


如果您想检查错误:

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

if (!$dbh) {
   die($DBI::errstr);
}
Run Code Online (Sandbox Code Playgroud)

如果您希望抛出异常:

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

if (!$dbh) {
   die($@);
}
Run Code Online (Sandbox Code Playgroud)