Frage

I have an exception class that looks like this

<?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;
    }
  }
 ?>

This works fine for many errors that are thrown due do typos/column count not matching value count, but when I throw an exception from the code myself, I get an error. For example

  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>";
}

I get Uncaught exception 'Exception' with message 'The Link is invalid, please request a new one' error when I run the code. If I remove that line, and induce an error by spelling SELECT as SLECT, the error class works fine.

How can I make in such a way that the error class will catch all types of errors ?

War es hilfreich?

Lösung

The problem is NOT all exceptions are PDOExceptions.You code cacthes only PDOException which means new Exception won't be catched. Try :

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>";
}

The reason why your code works when you spell SELECT as SLECT is because you triggered a PDOException instead of a new Exception.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top