PHP – how to catch errors using set_error_handler

PHP set_error_handler can catch various type of php errors in a specific portion of the code. To restore the previous error hander one can call restore_error_handler function. Here is a sample code snippet and its outcome.

function my_error_handler ($errno, $errstr, $errfile, $errline) {
  echo "errstr=$errstr";
  // return true to bypass  standard php error handler
  return true;
set_error_handler('my_error_handler', E_ALL | E_STRICT);
// this will cause warning due to bad regex
$ret = preg_match("abc", "abcdef");
errstr=preg_match(): Delimiter must not be alphanumeric or backslash
Env: PHP 5.5.9 (Linux)

Few points to note

  1. Returning true from error handler will bypass php standard error handler.
  2. restore_error_handler will restore previous hander. In our case default php error handler.
  3. It is pretty useful in case you are executing code obtained from thord party.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments