views:

358

answers:

3

Hi all,

is there a way to handle error reporting in a centralized manner in PHP? I'd like to be notified of all errors raised by my application by email.

What's the best way to achieve this for a whole application?

Thanks

+8  A: 

You can use set_error_handler to handle errors at runtime any way you like.

Kalium
+5  A: 

As Kalium mentioned, you'll want to be using set_error_handler, but that only gets you part of the way. You also want to trap uncaught exceptions. For that, use set_exception_handler.

What I do myself is have my code trap errors, and convert those errors to approprate exceptions that I can catch elsewhere. For anything that isn't caught, I use the default exception handler to log and report them, and to display an appropriate error if necessary.

Keith Gaughan
+3  A: 

There are 3 types of errors:

  1. System errors, such as warnings or fatal errors raised by PHP. 404 errors are also in this category.

  2. Database errors by a malformed or failed query or database connection.

  3. Logical errors such as when something went wrong in the internal working of your application not related to a server or database. For example if you expected a certain file to be in a given folder, but it wasn't.

The best way to create an ErrorHandler class that handles all three types of errors. For system errors, you would use set_error_handler or read up on one of the online tutorials such as this one.

For database, I suggest using a centralized Database class which handles all the queries. Use something like this:

$result=mysql_query($sql);
if (! $result)
{
   $ErrorHandler->dbError(mysql_error(), $sql);
}

For logical errors, such as the error of not finding an expected file or database record, you would call up the same ErrorHandler class and do something like:

if ($logicalError)
{
   $ErrorHandler->appError('Something bad happened',__LINE__, __FILE__);
   $ErrorHandler->showAppErrorPage();
}

Here the __FILE__ and __LINE__ constants will give exactly the location where this error occurred. Read up on them on the php.net site.

Your ErrorHandler class can log all errors to a log file, email you, or even SMS/Text you on your mobile. It could also be used to redirect the user to an error page.

Click Upvote