Question

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 ......

Was it helpful?

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
}

OTHER TIPS

You are confusing custom exception handler with custom exception class. You need the former one and the other answer is wrong.

Explanation.

In your application code you have to writing one single line only:

$pdo = new PDO('mysql:host='.THOST.';dbname='.TDB.'', TUSER, TPASS); 

without multiple tries and stuff. Just the code you need to run.

While all the handling logic goes into handler

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top