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.

<?php

//Our custom exception_handler function.
function exception_handler($exception){
   echo 'Exception handler function has been called!';
}

//Set the function.
set_exception_handler('exception_handler');

//Throw an example, just to test it out.
throw new Exception('Test');

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:

<?php

//Custom exception handler function.
function exception_handler($exception){
    //Log the exception to our server's error logs.
    error_log($exception);
    //Send a 500 internal server error to the browser.
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
    //Display our custom error page.
    include 'error.html';
    //Kill the script.
    exit;
}

//Tell PHP about our super duper function.
set_exception_handler('exception_handler');

//Throw an exception.
throw new Exception('TEST');

Our error.html page is a simple HTML file. Error files should do as little as possible, lest they aggravate database connections, etc.

<!DOCTYPE html>
<html>
    <head>
        <title>Error!</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
    <body>
        <h1>Oops!</h1>
        <p>Something went wrong!</p>
        <p>This error has been sent to our technical team.</p>
    </body>
</html>

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.