The set_error_handler() function can be used in PHP to allow you to catch any run time errors and act accordingly. This function can take two parameters:
- Error Handler : This a string which is the name of the function that will be called if an error is encountered.
- Error Types (optional) : This is an optional parameter used to tell PHP on what error codes to act. This is the same error reporting setting.
The function that is defined in the function must have the following footprint as a minimum.
function handler($errno,$errstr)
You can also get a lot more information out by using other parameters.
function handler($errno,$errstr,$errfile,$errline,$errcontext)
Here is some code that will print two errors to screen with as much information as possible.
<?php // go beyond the end of the array for ($i = 0; $i < 4; $i++) { $numbers[$i]; } // try to concatenate a string to a non existent variable $string .= 'nothing'; function my_error_handler($errno, $error, $file, $line, $errContext) { $message = '[ERROR]['.$errno.'] ['.$error.'] ['.$file.'] ['.$line.']'.' '.print_r($errContext, true).' <br />'; echo $message; } ?>
This will produce a lot of information so it is best not to use this unless you really need to. Code execution is not stopped when this function is run, so the ideal use of this function is to try and contain errors when they occur.
The function set in set_error_handler() will only be run under certain error conditions as not all errors are catchable from within the code. The following table gives an indication as to what errors can be caught.
Error No. | Constant | Catchable |
---|---|---|
1 | E_ERROR | No |
2 | E_WARNING | Yes |
4 | E_PARSE | No |
8 | E_NOTICE | Yes |
16 | E_CORE_ERROR | No |
32 | E_CORE_WARNING | No |
64 | E_COMPILE_ERROR | No |
128 | E_COMPILE_WARNING | No |
256 | E_USER_ERROR | Yes |
512 | E_USER_WARNING | Yes |
1024 | E_USER_NOTICE | Yes |
6143 | E_ALL | n/a |
2048 | E_STRICT | Partially |
4096 | E_RECOVERABLE_ERROR | Yes |
Notice that the E_STRICT errors are only partially catchable. This is because some strict errors will produce fatal errors.
0 comments:
Post a Comment