Treehouse

Custom Error Handling in PHP

By on  

Web application don't always go to plan, that much is obvious. Users will continuously find ways to trigger errors within your application and how you record, contain, and eliminate these errors is a true testament to your code. PHP provides means for trapping errors and dealing with them the way you need them to be dealt with. The best part of PHP error handling is that it's extremely customizable using PHP's set_error_handler() function.

The Error Handler

function xhandler($number,$string,$file,$line,$context)
{
	//log to text file?

	//log to xml file?

	//store in database?

	//whatever you want to do!
}

The Explanation

Your error handling function can accept five parameters:

  • $number - Integer error number representative of the PHP error level
  • $string - String description of the error
  • $file - File in which the error occurred
  • $line - Line number in the file that the error occurred
  • $context - Context of the area, including an array of each variable in scope

The Usage

/* use this error for ALL (E_ALL) errors */
set_error_handler('xhandler',E_ALL);

This is a basic example of the custom error handling in PHP. The programming and methods you use to save and analyze these errors is up to you, but common methods include:

  • Saving the error to a database
  • Saving the error information to a local file (text, xml, etc.)
  • Redirecting the user to another page
  • Absolutely nothing (I've actually seen this in other dev's code).

Though you can do almost anything in your error handling function(s), I recommend the following for error handling functions:

  • Store the date/time of the error
  • Use more than one method of storing error logs (database, file, etc.)
  • Email severe warnings/errors to yourself so you may deal with any critical problems as soon as possible
  • Use different error handling functions for different error levels if necessary
  • Create a new file log daily so that your log file doesn't balloon

How do you record PHP errors in your applications?

ydkjs-2.png

Recent Features

  • LightFace:  Facebook Lightbox for MooTools

    One of the web components I've always loved has been Facebook's modal dialog.  This "lightbox" isn't like others:  no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much."  With Facebook's dialog in mind,...

  • Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each...

  • 5 HTML5 APIs You Didn’t Know Existed

    When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for...

Incredible Demos

  • Using Opacity to Show Focus with jQuery

    A few days back I debuted a sweet article that made use of MooTools JavaScript and opacity to show focus on a specified element. Here's how to accomplish that feat using jQuery. The jQuery JavaScript $(document).ready(function() { //area 1 $('.fade-area-1').children().hover(function() { $(this).siblings().stop().fadeTo(500,0.5); }, function() { $(this).siblings().stop().fadeTo(500,1); }); //area...

  • Sexy Album Art with MooTools or jQuery

    The way that album information displays is usually insanely boring. Music is supposed to be fun and moving, right? Luckily MooTools and jQuery allow us to communicate that creativity on the web. The XHTML <div id="album"> <div id="album-front"></div> <div id="album-back"></div> <div...

  • Page Peel Effect Using&nbsp;MooTools

    Soh Tanaka release a great script back in May titled Simple Page Peel Effect with jQuery & CSS. The idea is that you place a "peel" image on the upper-right side of an element which, when...

Discussion

  1. Hello – nice tutorial. It would be cool to see a custom exception handler tutorial next – and then maybe a combo of the two. ;)
    -Aaron

  2. This is very useful. I shall implement now :)

  3. Thanks for this great tutorial. I’ll subscribing to your feeds!

  4. hi

    thanks for your tutorial . but we tried this and it dosn’t work for some error types like fatal errors
    did u see this ?

  5. flies

    And if you need something for exceptions (although you should avoid them), you can try this:


    function exception_handler($exception)
    {
    // these are our templates
    $traceline = "#%s %s(%s): %s(%s)";
    $msg = "PHP Fatal error: Uncaught exception '%s' with message '%s' in %s:%s\nStack trace:\n%s\n thrown in %s on line %s\n\n";

    // alter your trace as you please, here
    $trace = $exception->getTrace();
    foreach ($trace as $key => $stackPoint) {
    // I'm converting arguments to their type
    // (prevents passwords from ever getting logged as anything other than 'string')
    $trace[$key]['args'] = array_map('gettype', $trace[$key]['args']);
    }

    // build your tracelines
    $result = array();
    foreach ($trace as $key => $stackPoint) {
    $result[] = sprintf(
    $traceline,
    $key,
    $stackPoint['file'],
    $stackPoint['line'],
    $stackPoint['function'],
    implode(', ', $stackPoint['args'])
    );
    }
    // trace always ends with {main}
    $result[] = '#' . ++$key . ' {main}';

    // write tracelines into main template
    $msg = sprintf(
    $msg,
    get_class($exception),
    $exception->getMessage(),
    $exception->getFile(),
    $exception->getLine(),
    implode("\n", $result),
    $exception->getFile(),
    $exception->getLine()
    );

    // do something with message
    }

    And then:


    set_exception_handler("exception_handler");

  6. flies

    @MiZO: if you want to catch fatal errors, you can try the following:

    error_reporting(E_ALL);
    ini_set('display_errors', 0);

    function shutdown(){
    $isError = false;
    if ($error = error_get_last()){
    switch($error['type']){
    case E_ERROR:
    case E_CORE_ERROR:
    case E_COMPILE_ERROR:
    case E_USER_ERROR:
    $isError = true;
    break;
    }
    }

    if ($isError){
    echo "Script execution halted ({$error['message']})";
    } else {
    echo "Script completed";
    }
    }

    register_shutdown_function('shutdown');

  7. [...] my article, Custom Error Handling in PHP, to learn about custom error handling in [...]

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Use Code Editor