【问题标题】:error class not catching thrown errors错误类没有捕获抛出的错误
【发布时间】:2014-06-30 12:40:08
【问题描述】:

我有一个看起来像这样的异常类

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

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

【问题讨论】:

    标签: php oop exception error-handling


    【解决方案1】:

    问题是NOT all exceptions are PDOExceptions。你只编码PDOException 这意味着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

    【讨论】:

      猜你喜欢
      • 2018-05-03
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      • 2011-09-07
      • 2015-10-05
      • 1970-01-01
      相关资源
      最近更新 更多