Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 570
imperium2335 Avatar asked Apr 16 '26 00:04

imperium2335


1 Answers

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.
like image 146
Madara's Ghost Avatar answered Apr 18 '26 16:04

Madara's Ghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!