The (im)proper use of try..catch.
Delusion
Most examples of try..catch operator you can find on the Net are something like this:
try {
$stmt = $dbh->prepare($sql);
$stmt->execute($data);
} catch (PDOException $e) {
die($e->getMessage());
}
Shamefully, PHP manual is especially bad at it, having such examples all over PDO and other extensions examples.
TL;DR
Never use try-catch for the basic error reporting. Just leave exceptions alone:
$stmt = $dbh->prepare($sql);
$stmt->execute();
Disclosure
Such a code is a result of a mere confusion. Look, what you actually have from it:
An error message being thrown right on the screen,
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'foo' at line 1
Looks exactly what you were looking for? Not quite.
- it appears on the screen unconditionally, revealing some system internals to a potential attacker when site goes live
- also it is scaring innocent user with strange message.
- also it is killing the script in the middle, so it may cause torn design (or no design at all) shown
- it is killing the script fatally, irrecoverably.
- it is showing only part of error info, making it sometimes difficult to identify the error for the programmer
- it is adding four lines of repeated code for the every query in the application, making it bloated and WET.
NONE of these things you actually want.
Clarification
As a matter of fact, you are writing this code only to be visually notified of the error, if it happened during development. The funny part is that for such a cause you need no extra code at all. I am not kidding. PHP is quite good with reporting errors, and need no extra assistance. If you leave your PDO code alone, adding no useless try..catch stuff, an exception will be translated into a fatal error, and PHP will be happy to report this fatal error usual way, just like any other error message.
That's the point.
Unlike your unconditional approach, PHP will follow site-wide configuration options, set for the whole server. If you want error messages to be shown right on the screen, just set the proper option for this: display_errors. That's all. In case of error, it will be revealed to you. Moreover, it will contain whole error message, including exact file name and line number where error occurred. And even more - a stack trace, which will help you to track down the code that actually caused the error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'foo' at line 1' in /srv/hosting/html/another_file.php:5
Stack trace:
#0 /srv/hosting/html/another_file.php(5): PDO->query('foo')
#1 /srv/hosting/html/pdo.php(23): demo()
#2 {main}
Here you can see the full error message you were depriving yourself from.
Let's closely examine it
- Fatal error: Uncaught exception part we can omit, nothing interesting here
- 'PDOException' with message 'SQLSTATE[42000] is telling us that it is not PDO throwing error at its whim, but just relaying to us an error message from mysql.
- Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'foo' at line 1' - the error message itself
- in /srv/hosting/html/another_file.php:5 - most important part. It points to the exact point where error occurred.
- Stack trace: - even more useful thing that reveals a chain of events that led to this particular error.
And all that treasure without a single extra line of code! Just with default PHP settings! Isn't it wonderful?
All right, but what about production environment? That's very interesting question. In fact, most PHP users consider themselves the only users of their site. And that custom of catching and echoing every error is a sure proof for that - it's intended for the programmer only but inconvenient for the users. While in reality sometimes sites go live, and require totally different error handling in this case.
To handle an error on a live site we actually need:
- log error for the programmer
- show a generic error page for the user
- send appropriate HTTP response code for the Search Engine
And again - PHP already can do it all for us! If we turn display_errors=off, while log_errors= on, PHP will do all the things automatically - log error, show error page and HTTP code. As of the custom error page, it is best to be handled by the web-server (ErrorDocument for Apache and error_page for Nginx).
— But I am doing it only for debugging purpose!!!
Well, you are doing it wrong. A programmer have to be notified of errors any time, no matter which mode is on.
Example
— But what if I want something more complex than just showing/logging?
In such a case you can setup a Custom Exception Handler like this
set_exception_handler('myExceptionHandler');
function myExceptionHandler($e)
{
header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
error_log($e);
readfile ('500.html');
exit;
}
or, for a more general handling not only exceptions but all errors,
set_error_handler("myErrorHandler");
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
error_log("$errstr in $errfile:$errline");
header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
readfile("500.html");
exit;
}
written just once it will relieve you from writing handling code again and again.
— All right, but is here a case when try..catch can be useful?
Sure! Just use try..catch only if you going to handle the error itself. Say, there is a code to process uploaded images. An error in such processing is not a fatal one and can be handled - so, that's the right place for the try..catch!
try {
processUploadedImage($file);
} catch (Exception $e) {
$formHandlerErrors[] = "There is an error processing uploaded image";
}
In short, if your error is recoverable and you have a certain scenario to recover - then use try..catch.
Comments:
I am hoping you can be the deciding voice to break a tie in opinions. In a situation where a query ran into an issue, but you just want to log the error and keep going.
Is PDO::ERRMODE_WARNING an acceptable solution?
For all your wonderful articles I couldn't find anything regarding how you feel about this error mode. Do you have an opinion on this mode?
Reply:
Hello Jonathan!
That's a very good question and indeed this situation is not covered in the tutorials. I can see two different approaches here:
I agree with Andy (apart from the fact that he emails him every exception lol) I wrapped most of my PDO statements in try-catch blocks so I can continue the script execution. And no, the script will not stop anyway due a fatal error because these failures are detected and the code flow changes depending on those.
Hello!
Great article! Been seeing try/catch on all PDO operations on every tutorial and this makes no sense like you say. My question is do you have an example for handling errors when using AJAX calls?
Your example is only bad because of the die() part. I use try catch for every pdo connection because I want to see every error. So I use it as follows:
Execution is not stopped, user doesn't see any "scary" message but I get informed of the page, the line number and the error, by email.
Reply:
Hello Andy!
Thank you for sharing! However, your example is still bad, for several reasons:
Just learn how to report PHP errors properly and you will have an excellent error reporting without a single try catch operator :)
HI,
Great tutorial/explanation. But what if I want to get/catch a PDO exception by mysql where a duplicate entry was trying to be inserted. So instead of checking the log files or displaying the PDO exception(which is worse i know) how do i get the PDO error info, and inform the user in a more user-friendly way? Basically, I have a table in mysql that checks for duplicates, and when adding a record with duplicate info, a pdo exception is thrown, how do get that info instead of looking in log files or displaying in screen?
Reply:
Hello Dave!
Thank you for the good question. Basically, this page explains why catching exceptions is bad for error reporting. But for the error handling it's perfectly all right.
Your case with duplicate records is a perfect example where you can and should catch an exception. You can find an example in the PDO article, https://phpdelusions.net/pdo#catch
Please feel free to ask if anything is still unclear for you.
"if your error is recoverable and you have a certain scenario to recover - then use try..catch. " - this means, when I am doing a mysql-transaction, my certain scenario do recover would be a rollback, so i should use try...catch ?
Reply:
Yes, of course. That's one of the most used cases for the try..catch
HI, Thanks for this great tutorial. I do feel however, that if what Dima Dz says in his messages, is true, then the Author of this article should affirm that for the readers of this article. I am talking about this comment in particular : "use try-catch on connection to DB because PDO doesn't provide this error handling ".
Thanks
Wonderful tutorial !
Dima,
Your suggestion contradicts with whole post. Showing or not showing any information is none of the concern for exceptions. Whether to show errors or not is a general PHP setting, and it has nothing to do with PDO or exception,
Except for that, great post!
You mention that if the error is recoverable and you have a handling scenario, then use try-catch block. Maybe mention that it's better to use try-catch on connection to DB because PDO doesn't provide this error handling and, for this reason, can show some sensitive info in the browser.
"NONE of these things you actually wants" should be "NONE of these things you actually want"
"Are you robot?" should be "Are you a robot?" and some space after it.
"then use this operator" makes no sense, you should re-write that part.
z
anyways,
set_exception_handlerwill trigger for all exceptions. What if we just want t trigger it for some of them?