Error handling is important part of application design. But some web application developers completely forget about error handling and this force their applications back to the past.
So, what is the goal of application error handling? I will give the answer:
1. Show user friendly errors message without php “Fatal Error”
2. Log the error to the file or database. This will allow developers analyze and fix the error.
3. Use error log for future analyses: find common application problems, frequent errors, etc.
To make the application error handling available for the community, I decided to create 2 packages for php 4 and php 5 with the same functionality but different (php version specific) implementation.
Design of those “AppErrorHandler” packages is the same:
- class to handle errors
- class to log errors
- (probably php5 version will be extended with exception handler)
Check AppErrorHandler.php source code using link for desired php version: php5 , php4.
To check live examples and all package source code use the following links: php5, php4.
To use application error handler you should add the following code to your application files:
require_once('AppErrorHandler.php');
$oEH = new AppErrorHandler();
This will automatically change default PHP error handler to the OnError method defined in AppErrorHandler.php file.
By default AppErrorHandler will log any errors(E_ALL | E_NOTICE) to the log file and by default show error messages for the users for (E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR) errors only.
If you want to display error message in case of E_ERROR only, use the following code
require_once('AppErrorHandler.php');
$oEH = new AppErrorHandler(array(E_ERROR));
If you want to display error messages in case of E_ERROR and E_USER_ERROR , and log E_ERROR errors only, use the following code;
require_once('AppErrorHandler.php');
$oEH = new AppErrorHandler(array(E_ERROR, E_USER_ERROR), E_ALL);
After creating instance of AppErrorHandler class all errors will be handled by it’s own methods. No additional coding required.