我正在使用扩展的 PDO 类,如下所示。但它的
try .. catch
块没有捕捉到异常。这是片段-
class ExPDO extends PDO
{
public function insert(string $sql, array $param){
try {
$statement = $this->prepare($sql) ;
$statement->execute($param); //throws exception
} catch (\PDOException $e) {
// throw
}
catch (\Exception $ex) {
//throw
}
}
}
那里发生异常,正在由全局处理程序处理 -
set_exception_handler(function($exp){
});
但是我想在
insert()
方法中处理异常。
有什么帮助吗?
似乎您对 Throwable 有疑问。从 PHP 7 开始,您需要使用 Throwable 类。异常并不总是被捕获。
参见https://www.php.net/manual/en/class.throwable.php和https://www.php.net/manual/en/class.throwable.php#124604
应该是
class ExPDO extends PDO
{
public function insert(string $sql, array $param){
$statement = $this->prepare($sql) ;
$statement->execute($param); //throws exception
}
}
在代码的另一部分,你可以做
use \ExPDO
$db = new ExPDO();
try {
$db->insert("Some query;", ["param" => "data"];
} catch (\PDOException $e) {
Log::error($e->getMessage()); // Only Example, try to use monolog or other tools that fits
} catch (\Throwable $t) {
Log::error($t->getMessage()); // Only Example, try to use monolog or other tools that fits
}
作为评论,你应该在课外抓住它