Thursday, 9 August 2018

PHP: Custom Exception Handling

This a beginners guide to exception handling in PHP. In this tutorial, I will also show you how to return a 500 internal server error and a custom template page whenever an uncaught exception occurs.
Firstly, it is worth noting that exception handling is not the same thing as using a TRY CATCH block. Exception handling is there to “clean up” any exceptions that weren’t caught. In some cases, you might not want to catch an exception, simply because your app shouldn’t continue in certain situations (an important query fails, for example).

set_exception_handler

The set_exception_handler function allows you to specify what function should be called if an uncaught exception occurs. i.e. The function that is going to try and mop everything up if things go pear-shaped.
Here is a small example. Try running it on your local machine.
Explanation:
  1. We create our custom function. Inside this function, I simply print out the string “Exception handler function has been called!”
  2. We set our custom function as the exception handler by using the PHP function set_exception_handler.
  3. We throw an exception for example purposes.

Custom error page.

Let’s do something useful with our custom function! In the next example, our custom exception handler is going to:
  1. Log the exception.
  2. Send a 500 Internal Server Error header to the client.
  3. Display a custom error page.
  4. Exit the script.
Code:
Our error.html page is a simple HTML file. Error files should do as little as possible, lest they aggravate database connections, etc.
You can modify and style the above page to your heart’s content!
Some notes:
  1. Printing out the exception to the screen is a bad idea, simply because it gives would-be attackers too much information about the workings of your PHP application. Instead, it is better to display a generic catch-all error page.
  2. Do NOT over-complicate your error pages. If your database is under too much strain and an exception is thrown as a result, do you really want your error page to be attempting database connections? Keep them simple and static!
  3. Exceptions are not Pokemon. You do NOT need to catch them all. Only catch an exception if your app can properly function without the process that failed. For example: If the INSERT query on your user registration form fails, should your application continue? Personally, I don’t think so.
  4. Sending a 500 internal error is helpful, especially in situations where Ajax requests are being used and/or cURL calls are being made.

0 comments:

Post a Comment