2011-01-27 109 views
8

在Perl中捕获任何DBI错误的最佳方式是什么?例如,如果由于插入的值中存在非法字符而导致插入失败,我如何才能让脚本失败,但捕获错误并进行适当处理。Perl DBI - 捕获错误

我不想做“或死”,因为我不想停止执行脚本。

回答

12

使用RaiseError=>1配置DBI->connect,并在try块(TryCatchTry::Tiny是try块很好的实现)包装您的来电来$dbh$sth

有关其他可用连接变量的更多信息,请参阅the docs

例如:

use strict; 
use warnings; 

use DBI; 
use Try::Tiny; 

my $dbh = DBI->connect(
    $your_dsn_here, 
    $user, 
    $password, 
    { 
     PrintError => 0, 
     PrintWarn => 1, 
     RaiseError => 1, 
     AutoCommit => 1, 
    } 
); 
try 
{ 
    # deliberate typo in query here 
    my $data = $dbh->selectall_arrayref('SOHW TABLES', {}); 
} 
catch 
{ 
    warn "got dbi error: $_"; 
}; 
+1

难道你不应该在`try`块中放置`connect`吗? – mscha 2011-01-27 23:13:30

1

你也可以做到以下几点,这将让你死,或优雅地处理这些错误,然后继续。

$dbh = DBI->connect($data_src, $user, $pwd) or die $DBI::errstr; 

my $sth = $dbh->prepare("DELETE FROM table WHERE foo = '?'"); 
$sth->execute('bar'); 
if ($sth->err) 
{ 
    die "DBI ERROR! : $sth->err : $sth->errstr \n"; 
}