views:

352

answers:

2

I used a class that converts errors to exceptions in PHP 5 and it logs the errors to a file and/or emails them to a specified account. Is there a better way to do this? There is something about this I know can be better. I am using set_error_handler.

set_error_handler("exception_error_handler");

My code does what it should in that it logs and emails errors but am I doing the process the best way. Would it be better to log it to a Database - assuming a data connection would be present in an error. What is the industry standard for web sites?

+1  A: 

I wouldn't dump that logic into the error handler.

Take a look at this method from Kohana.

/**
* PHP error handler, converts all errors into ErrorExceptions. This handler
* respects error_reporting settings.
*
* @throws ErrorException
* @return TRUE
*/
public static function error_handler($code, $error, $file = NULL, $line = NULL)
{
    if (error_reporting() & $code)
    {
        // This error is not suppressed by current error reporting settings
        // Convert the error into an ErrorException
        throw new ErrorException($error, $code, 0, $file, $line);
    }

    // Do not execute the PHP error handler
    return TRUE;
}

Clean and does what the method describes. You can now move your handling into an exception handler or inside a catch block.

The Pixel Developer
Well, I answered this question when he had a code sample, but now it's disappeared so I apologize if my answer doesn't make any sense.
The Pixel Developer
+1  A: 

Your code for dealing with errors must be absolutely bulletproof.

Sometimes it will kick in because of a really obscure reason that you forgot to test for, but you still want it to run when when its struggling through the code version of the apocalypse.

Writing its output to a database creates a huge dependency for you code - and the absence of the database is most likely to be a major cause of problems which would be reported.

Relying on mail is still a dependency, however the most immediate objective in the event of an outage should be to get the system working again - so sending an email is a very effective way of alerting you that you need to fix something.

PHP's file handling facilities do not lend themselves to concurrent access - so although I'd recommend logging any events locally, do not write the files from your code - use the syslog interface. By all means send an email with the relevant details after you've sent it to the syslog.

HTH

C.

symcbean