How to catch undefined functions with set_error_handler in PHP

I guess you needs to use register_shutdown_function also

For example:

 register_shutdown_function( array( $this, 'customError' ));.

   function customError() 
   {

     $arrStrErrorInfo = error_get_last();

     print_r( $arrStrErrorInfo );

   }

set_error_handler is designed to handle errors with codes of: E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE. This is because set_error_handler is meant to be a method of reporting errors thrown by the user error function trigger_error.

However, I did find this comment in the manual that may help you:

"The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called."

This is not exactly true. set_error_handler() can't handle them, but ob_start() can handle at least E_ERROR.

<?php

function error_handler($output)
{
    $error = error_get_last();
    $output = "";
    foreach ($error as $info => $string)
        $output .= "{$info}: {$string}\n";
    return $output;
}

ob_start('error_handler');

will_this_undefined_function_raise_an_error();

?>

Really though these errors should be silently reported in a file, for example. Hopefully you won't have many E_PARSE errors in your project! :-)

As for general error reporting, stick with Exceptions (I find it helpful to make them tie in with my MVC system). You can build a pretty versatile Exception to provide options via buttons and add plenty of description to let the user know what's wrong.

Tags:

Php