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
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
You can use set_error_handler to handle errors at runtime any way you like.
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.
There are 3 types of errors:
System errors, such as warnings or fatal errors raised by PHP. 404 errors are also in this category.
Database errors by a malformed or failed query or database connection.
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.