2014-12-02 111 views
3

我正在写一个Perl脚本,我似乎无法赶上DBI错误时,不管我怎么努力。我尝试这样做:不能赶上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 ([email protected]) { 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。我需要抓住它,以便我可以显示正确的信息。

回答

6

默认的错误处理:

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

你想传递给PrintError => 0connect


如果你喜欢检查错误:

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([email protected]); 
}