Custom Error Handling and Debugging

In our development environment we want to see all error details in the browser, but on the live site we don't want to show any error messages. Instead we want them to see a 'friendly' message, and we want the ugly details of the error to be emailed to us (so that we are aware that an error occured on the live site). In this step, we'll set up custom error handling.

  1. Update the config file (config.inc.php) to look like this.

    We've added some new constants to our config file, DEBUG_MODE and ADMIN_EMAIL

    The reason for DEBUG_MODE is that we might possibly want to display error messages on the live site under certain circumstances. For example, if there is an error occurring on the live site, but not on dev, then we can simply change DEBUG_MODE to true for the live site settings. Notice that we've added an IF statement that checks to see if we are in debug mode, if so we want PHP to display all error messages. Make sure to set ADMIN_EMAIL to your own email address.

  2. Now we are going to add a few functions to the config file. Functions defined in the config file will be available to all web pages.

  3. Adding an Error Page

    Create a file inside the 'my-new-site' folder named error.php. You can copy the contents of the site home page into it and then make the following changes:

  4. Test It!

    Go ahead and generate an error in the code of the site's home page (echo a variable that doesn't exist). You should see your custom error handling function.

    At this point you should test this code on your live server, but we may not have set it up just yet.

    SIDE NOTE: I did not add a SERVER error header to the error page. Normally whan an error occurs on the web server, we should technically return a HTTP status code of 500. We'll talk more about http headers later in the course.