如何从DB Adapter中获取MySQL中的最后生成的错误

时间:2013-08-29 22:16:53

标签: php mysql zend-framework2

我正在拉这个头发。

在ZF1中它很容易,因为它会引发完整的SQL错误详细信息的异常。在ZF2中,它只引发Exception \ RuntimeException,它只传递错误描述而不是无法使用的数字。

问题:如何从适配器中获取完整错误。以下是我使用的代码片段:

$dbAdapter = $this->_serviceManaget->get('Zend\Db\Adapter\Adapter');

try {
    $result = $dbAdapter->query($sql, $binds);
} catch (\Exception $e) {
    //here I need to check the error number raised by MySQL during the execution
    //$e object in this case only contains 
    //$e->message = "Duplicate entry 'blablabla' for key 319" and $e->code = 0   
}

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

在ZF2 Exceptions中扩展自PHP SPL Exceptions。它们都扩展了标准的Exception接口。在Exception manual之后,您可以执行此操作:

try {
    $result = $dbAdapter->query($sql, $binds);
} catch (\Exception $e) {        
    $code = $e->getCode();
    $msg  = $e->getMessage();
    $file = $e->getFile();
    $line = $e->getLine();
    echo "$file:$line ERRNO:$code ERROR:$msg";       
}

仅供参考,您可以针对不同的异常类型实现多个捕获:

try {
    ...
} catch (\RuntimeException $e) {
    ...
} catch (\LogicException $e) {
    ...
}

<强>更新
用于直接从\mysqli实例获取错误数据:

try {
    $result = $dbAdapter->query($sql, $binds);
} catch (\Exception $e) {
    $mysqli = $dbAdapter->getDriver()->getConnection()->getResource();        
    $file = $e->getFile();
    $line = $e->getLine();
    echo "$file:$line ERRNO:$mysqli->errno ERROR:$mysqli->error";       
}

有关如何获取\mysqli错误和警告数据的详细信息,请检查manual