Custom Error Handling In PHP Using set_error_handler()

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
set_error_handler('my_error_handler');
 
// go beyond the end of the array
$numbers = array(1, 2, 3);
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.ConstantCatchable
1E_ERRORNo
2E_WARNINGYes
4E_PARSENo
8E_NOTICEYes
16E_CORE_ERRORNo
32E_CORE_WARNINGNo
64E_COMPILE_ERRORNo
128E_COMPILE_WARNINGNo
256E_USER_ERRORYes
512E_USER_WARNINGYes
1024E_USER_NOTICEYes
6143E_ALLn/a
2048E_STRICTPartially
4096E_RECOVERABLE_ERRORYes

Notice that the E_STRICT errors are only partially catchable. This is because some strict errors will produce fatal errors.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
11 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.