What is a decent way to handle PDO error when using try catch block?
Currently I have something like this:
BlogModel.php
class BlogModel extends Model {
public function save($id, $value) {
$stmt = $this->getDb()->prepare('UPDATE setting SET name = :name WHERE id = :id');
$stmt->bindParam(':id', $id);
$stmt->bindParam(':name', $values);
return ($stmt->execute() !== false) ? $id : false;
}
}
So, in the controller BlogController.php, I would do something like this:
<?php
class Blog extends Controller {
public function comments()
{
$data = array();
$model = new BlogModel;
if ($model->save(2,'test')) {
$data['result']['message'] = 'Settings saved';
$data['result']['status'] = 'success';
} else {
$data['result']['message'] = 'Could not save the settings';
$data['result']['status'] = 'error';
}
$view = new View("view.php", $data)
$view->render();
}
}
?>
This is the way I handle PDO error using if conditions. What is the decent way to translate this into try catch block? I don’t want to code the variables ($data['result']['message'] $data['result']['status']) all the time.
Is possible to add “throw exception” in the catch block somehow?
If there is a lot of try catch blocks in the controller, it going to look messy.. right?
None of the answers here are wrong. But actually all three combined are the real answer.
You should definitely set
as said by Cerad.
From now on every single issue about anything regarding database is thrown via exception of type
PDOException. You just don’t have to throw your ownExceptionas said by ladar because it’s useless. Just take the ladar code and convert it intoAnd do NOT throw anything by yourself.
Then a very nice way for debugging PDO queries is using the catch script linked by Basic that you can find here once again.
Combining this things togheter you’ll have a flexible, clean and easy-debug way to catch all the errors that could come.