错误类没有捕获抛出的错误

时间:2014-05-13 00:40:38

标签: php oop exception error-handling

我有一个看起来像这样的

的异常类
<?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来引发错误,则错误类可以正常工作。

我怎样才能使错误类能够捕获所有类型的错误?

1 个答案:

答案 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