Reputation: 24112
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
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
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:
Upvotes: 7
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