Search code examples
phpexceptionpdocustom-exceptions

php pdo catching connection exception with custom exception handler


What im trying to achieve here , is when the pdo connection throws an exception , my custom exception handler takes the message and passes it on so i can catch it with my custom exception handler.

try {
       $mysqli = new PDO('mysql:host='.THOST.';dbname='.TDB.'', TUSER, TPASS);
     }   

          catch (PDOException $e) {

              $a = $e->getMessage();
          throw new customException  ( "Failed to connect to MySQL:". $a );   
          die();
          }

         catch (customException $e){ 

                 echo  $e->errorMessage(); 
       }

BUT it returns this error : Fatal error: Uncaught exception 'customException' with message ......


Solution

  • Wrap it in another try-catch block.

    try {
      try {
        $mysqli = new PDO('mysql:host='.THOST.';dbname='.TDB.'', TUSER, TPASS);
      } catch(PDOException $e) {
        $a = $e->getMessage();
        throw new customException  ( "Failed to connect to MySQL:". $a );
      }
    } catch(customException $e) {
      echo  $e->errorMessage();
      // Do what you want
    }