Best Practice for Error Handling Using Pdo

PDO error handling and storing errors in database

I think it is better to write your logs to a file, instead of a database. Especially since you want to log PDO errors, which indicate something is wrong with your database connection.

You can show the user a nice error page by catching your errors. You can redirect your users to your error page then, in case something went wrong.

PHP PDO error handling halting execution

You've got several questions in here, and I'll try to answer them all.

If I switched to ERRMODE_SILENT, which I believe would continue the processing, how do I detect the error in order to throw it to the catch?

Instead of using try/catch in this case, you'd need an if statement checking the PDO error code, e.g. if ($db->errorCode() !== null) (see PHPDoc for PDO Error Handling) where you would log the error, perhaps set the HTTP Response Code to something you expect from Javascript.

Why is my AJAX request hanging after this failure?

I'd suspect that your page is not actually hanging; rather, no JS is being executed for one reason or another. In your first attempts, you would be getting a 500 error code, which would not trigger the .success() function you provided to $.post. In order to see the problem in this case, you'd need to add a .fail() callback to your AJAX request.

Once you swapped to using trigger_error, a 200 OK would be returned since no exception was thrown. I'm not sure what you mean by "my AJAX processed it incorrectly".

Is this a correct way to handle this, or is there a better way?

This depends a lot on preference. A PDO exception for me should be very rare because I'm processing and validating the data before I ever send it to the database. In your case, Column 'field' cannot be null is a good example of something you should check beforehand.

If a PDO exception does occur, I would try to handle it gracefully -- that means catching it, logging an error, setting the HTTP Response Code to something sensible (probably 400 Bad Request would do), and returning a result with an error message. From the Javascript, I'd have a .fail method that parses the result for an error and displays something appropriate to the user. Having completely separate methods for success and failure cases is a good design principle and can help keep clutter from your code.

I hope this helps you on the right track.

PDO Exception Questions - How to Catch Them

You should look at the documentation. But If you dont find anything, you can add another catch :

<?php
try {
$stmt = $db->prepare("INSERT INTO tbl_user (id, name, password, question, answer) VALUES (NULL, :name, :password, :question, :answer)");
$stmt->bindValue(":name", $_POST['name']);
$stmt->bindValue(":password", $_POST['password']);
$stmt->bindValue(":question", $_POST['question']);
$stmt->bindValue(":answer", $_POST['answer']);
$stmt->execute();
echo "Successfully added the new user " . $_POST['name'];
} catch (PDOException $e) {
echo "DataBase Error: The user could not be added.<br>".$e->getMessage();
} catch (Exception $e) {
echo "General Error: The user could not be added.<br>".$e->getMessage();
}
?>

This must work because all exceptions of PHP plugins herits from the Exception native PHP class. (Since 5.0 if my memory is well).

error handling if pdo db connection is not present?

To stop further processings just add an exit() at the end of each catch block, unless you want to apply a finally block.

try {
//...
} catch(PDOException $e) {
// Display a message and log the exception.
exit();
}

Also, throwing exceptions and true/false/null validations must be applied through the whole connect/prepare/fetch/close operations involving data access. You may want to see a post of mine:

  • Applying PDO prepared statements and exception handling

Your idea with including db connection file I find good, too. But think about using require_once, so that a db connection is created only once, not on any include.

Note: In my example I implemented a solution which - somehow - emulates the fact that all exceptions/errors should be handled only on the entry point of an application. So it's more directed toward the MVC concept, where all user requests are sent through a single file: index.php. In this file should almost all try-catch situations be handled (log and display). Inside other pages exceptions would then be thwrown and rethrown to the higher levels, until they reach the entry point, e.g index.php.

As for reconnecting to db, How it should be correlated with try-catch I don't know yet. But anyway it should imply a max-3-steps-iteration.



Related Topics



Leave a reply



Submit