Thursday, 9 August 2018

Error Handling: Throwing PHP Exceptions With The Mysql_* Extension.

Unfortunately, the (outdated) mysql_* extension in PHP does not support exception handling.
Obviously, this is an issue for those of us who want to avail of the flexibility that exceptions can offer. For the most part, developers who use the mysql_* extension tend to carry out their “error handling” like so:
The problem with this approach is that the rest of our application is completely oblivious to any SQL errors that may occur. If the query fails, the script is halted and there is no way to recover. To make matters even worse, the user will be presented with a nasty-looking SQL error.
A better, more-flexible approach would be to throw an exception if the query fails:
The code above checks to see if mysql_query returns a boolean FALSE value. If it does, we assume that an error has occurred. If an error has occurred, we proceed to throw an Exception containing the MySQL error message.
If you’re worried about the extra added code, then you can abstract your exception-throwing into a custom function like so:
Using this custom function, we can execute our queries like so (and catch any errors):
Using exceptions can be extremely beneficial when it comes to handling failed SQL queries.
In the vast majority of cases, a failed SQL query indicates that the application is down and that something has gone terribly wrong. In cases like this, shouldn’t catch the exception in question. Instead, you should “handle” it via a custom exception handler. This can be achieved with the function set_exception_handler. An example:
Basically, whenever an exception is thrown, our application will automatically call the app_error function above. There, we can log the error, set a 500 internal server error header and provide the user with a custom “error template”.

0 comments:

Post a Comment