PHP Custom Error Handling

PHP has many built in error reporting levels, sometimes it is better to use these when your application fails on a fundamental level, specifically E_USER_ERROR.

Sometimes instead of handling fatal errors where they happen, I find bailing out into a global error handler more efficient. For instance take this concept example:

// This could be a failed

MySQL update or whatever

if (‘foo’ == ‘foo’) {

die(‘foo really shouldn’t equal foo’);

}

// This could be displaying the failed update

echo ‘this doesn’t work if foo != foo’;

Ok, so far so good, it may be poor man’s error handling, but at least it gets the job done. The user will never see the echo of the string that relies on foo!=foo, or the “failed update”.

It’s a hassle to continually code die() error messages, especially if you want to render the errors with pretty HTML; and there are clear benefits as to why you should do this:

  • Errors fit into the rest of your site, users get worried when look ‘n feel drastically changes, i.e. from nice CSS layout, to black and white critical mass of text.
  • It makes the site look more professional, and less buggy. You could even dress the error up to the point where it doesn’t look like one anymore. How about instead of “Error 404″, you could build:

I am sorry, but the page you were looking for has been moved. Here is a list of search results applying to the page you wanted:
-etc-
Use the search box below if you want to continue searching.
-etc-

  • You can create descriptive errors; instead of “Connection to MySQL Failed”, and a collective wtf from the users, you could change it to “I am sorry but an unforeseen error has prevented the information you requested from being retrieved from our database, please email the admin–etc.”
  • Custom error messages hide your code from being displayed, which could potentially leave you vulnerable.