我有一个看起来像这样的
的异常类<?php
class Errors{
public function displayError(Exception $e){
$trace = $e->getTrace();
if($trace[0]['class'] != ""){
$class = $trace[0]['class'];
$method = $trace[0]['function'];
$file = $trace[0]['file'];
$line = $trace[0]['line'];
$error_message = $e->getMessage().
"<br /> Class/Method : ".$class." <==> ".$method.
"<br /> File : ".$file.
"<br /> Line : ".$line;
}
return $error_message;
}
}
?>
这适用于由于拼写错误/列计数不匹配值计数而引发的许多错误,但是当我自己从代码中抛出异常时,我收到错误。例如
try{
$stmt = $db->dbh->prepare("SELECT user FROM reset ");
$stmt->execute();
if ($stmt->rowCount() < 1){
throw new Exception('The Link expired, request a new one');
} else {
throw new Exception('The Link is invalid, please request a new one');
}
}
catch (PDOException $e) {
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
运行代码时出现Uncaught exception 'Exception' with message 'The Link is invalid, please request a new one'
错误。如果我删除该行,并通过将SELECT
拼写为SLECT
来引发错误,则错误类可以正常工作。
我怎样才能使错误类能够捕获所有类型的错误?
答案 0 :(得分:0)
问题是NOT all exceptions are PDOExceptions
。您只编译PDOException
cacthes,这意味着new Exception
无法获取。试试:
try
{
$stmt = $db->dbh->prepare("SELECT user FROM reset ");
...
}
catch (PDOException $e)
{
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
catch (Exception $e)
{
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
将SELECT
拼写为SLECT
时,您的代码有效的原因是您触发了PDOException
而不是new Exception
。