imperium2335
imperium2335

Reputation: 24112

Custom PDO Error try/catch

Currently when there is an error with my SQL it throws the traditional error that looks like this:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax...|

I know I can achieve what I want by wrapping every SQL routine in a try/catch block but this seems a little long winded:

class ProductsModel extends Model {

  function __construct()
  {
    parent::__construct();
  }

 public function setName($name, $productId)
  {
    $SQL = 'UPDATE products SET name = ? WHERE id = ?';
    try{
    $r = $this->db->prepare($SQL);
    $r->execute(array($name, $productId));
    }catch(PDOException $e) {
      echo 'Error!';
    }
  }
}

Is there a way to have this done automatically for all SQL queries made?

Upvotes: 3

Views: 1406

Answers (3)

clover
clover

Reputation: 5170

Implement your own class PDO class:

class MYPDO extends PDO {
  public function query() {
    try {
      call_user_func_array(array($this, 'parent::query'), func_get_args());
    }catch(PDOException $e) {
      echo 'Error!';
    }
  }
}

$db = new MYPDO(...);
$db->query(...);

Upvotes: -1

Madara's Ghost
Madara's Ghost

Reputation: 174957

Yes there is, and no, you shouldn't do it.

What you should do, is not to catch it inside the function, and instead, wrap the method call inside of the higher level with the catch block. i.e.:

try {
    $productsModel->setName("name", 42);
}
catch (PDOException $e) {
    //Do something, 500 error code, whatever
}

That's because, only when you try to access the database you know what you want to do in case it fails.

This:

  • Leaves your method cleaner, no error handling needed inside of the method.
  • Gives you flexibility. At some point you may want to throw a 500 error if it fails, at another, you may want to return a JSON object to an AJAX call.

Upvotes: 7

user399666
user399666

Reputation: 19879

You can setup an exception handler.

<?php
function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>

It will catch all Exception types, not just PDOExceptions. If you want to specifically handle all PDOExceptions, you can check like so:

function exception_handler($exception) {
   if ($exception instanceof PDOException) {
       echo 'This is a PDOException';
   }
}

Upvotes: 4

Related Questions