1

If I set RaiseError = 1, what exception is raised when connecting or executing?

If I were to surround my execute() method in try catch, what exception should I be catching?

4

3 回答 3

2

不推荐使用提供try和的 Perl Error.pm 模块catch异常,因为它们存在于 Perl 中,是无类型的,下面是你如何捕获一个:

eval {
  do_something_which_may_throw_exception();
};
if ($@) {
  print "Exception: $@\n";
};

简而言之,eval { ... }块充当“尝试”,而if ($@) { ... }充当“捕获”,其中异常文本包含在特殊变量$@中。

于 2013-07-30T14:19:47.440 回答
2

如果您想从 DBI 取回正式的异常对象,您可以使用HandleError属性和Exception::Class::DBI。我自己用它。来自剧情简介:

use DBI;
use Exception::Class::DBI;

my $dbh = DBI->connect($dsn, $user, $pass, {
    PrintError  => 0,
    RaiseError  => 0,
    HandleError => Exception::Class::DBI->handler,
});

eval { $dbh->do($sql) };

if (my $ex = $@) {
    print STDERR "DBI Exception:\n";
    print STDERR "  Exception Type: ", ref $ex, "\n";
    print STDERR "  Error:          ", $ex->error, "\n";
    print STDERR "  Err:            ", $ex->err, "\n";
    print STDERR "  Errstr:         ", $ex->errstr, "\n";
    print STDERR "  State:          ", $ex->state, "\n";
    print STDERR "  Return Value:   ", ($ex->retval || 'undef'), "\n";
}
于 2013-07-30T15:04:36.810 回答
2

DBI 文档列出并解释了许多选项,其中许多与错误处理有关。

Perl 有两个主要的错误处理习惯用法:

  1. 返回一个假值。错误的原因在于某些全局变量。
  2. die带有一些错误消息(致命)。

默认情况下,DBI 使用第一个习语。错误原因在$DBI::errstr. 为此,您必须检查对 DBI API 的每次调用的返回值。

当你感到懒惰时,你可以使用异常。在句柄构造函数中设置RaiseError将使 DBI 方法抛出异常。从文档:

引发错误

类型:布尔型,继承

RaiseError属性可用于强制错误引发异常,而不是简单地以正常方式返回错误代码。默认为“关闭”。当设置为“on”时,任何导致错误的方法都将导致 DBI 有效地执行 a die("$class $method failed: $DBI::errstr"),其中$class是驱动程序类,$method是失败的方法的名称。例如,

DBD::Oracle::db prepare failed: ... error text here ...

[…]

通常RaiseError与 结合使用eval { ... }以捕获已引发的异常,然后使用if ($@) { ... }块来处理捕获的异常。例如:

eval {
  ...
  $sth->execute();
  ...
};
if ($@) {
  # $sth->err and $DBI::err will be true if error was from DBI
  warn $@; # print the error
  ... # do whatever you need to deal with the error
}

在该 eval 块中$DBI::lasth,如果您不能确定哪个句柄触发了错误,则该变量可用于诊断和报告。

如您所见,Perl 中的异常不是用 try/catch 处理的,而是用eval { ... }. 在evalthat之后die$@错误变量将设置为该错误,您可以自由处理它。请注意,DBI 不使用异常对象。

于 2013-07-30T14:21:10.807 回答