1

I am trying to make an errorhandler in PHP that catches fatal errors. Catching normal errors works! Fortunately!

But fatal errors is still a no go.

Could anyone please tell me what the problem is with my script below: Thanks a million. If so it means it has saved my day :-#

function shutdown(){
        $isError = false;
        if($error = error_get_last()){
            switch($error['type']){
                case E_ERROR:
                case E_CORE_ERROR:
                case E_COMPILE_ERROR:
                case E_USER_ERROR:
                    $isError = true;
                    break;
            }
        }
        if ($isError){
            echo "Script execution halted ({$error['message']})";
        }
        else {
            echo "Script completed";
        }
}


set_error_handler('errorHandler');
register_shutdown_function('shutdown');





function errorHandler( $errno, $errstr, $errfile, $errline, $errcontext){
  echo 'Into '.__FUNCTION__.'() at line '.__LINE__.
  "\n\n---ERRNO---\n". print_r( $errno, true).
  "\n\n---ERRSTR---\n". print_r( $errstr, true).
  "\n\n---ERRFILE---\n". print_r( $errfile, true).
  "\n\n---ERRLINE---\n". print_r( $errline, true).
  "\n\n---ERRCONTEXT---\n".print_r( $errcontext, true).
  "\n\nBacktrace of errorHandler()\n".
  print_r( debug_backtrace(), true);
}

function a( ){
  //echo "a()'s backtrace\n".print_r( debug_backtrace(), true);
  echo 'asdfasdf; // oops
}

function b(){
  //echo "b()'s backtrace\n".print_r( debug_backtrace(), true);
  a();
}

b();
?>

Parse errors should be catchable imho since I already used a pre baked script that catches parse errors. Unfortunately though, the script is quite buggy.

1
  • 2
    Is the parse error intentional? PHP won't try to run code with parse errors. Commented Feb 16, 2015 at 14:32

1 Answer 1

2

The answer is: PHP won't execute any file with parse error.

This still means you can catch parse errors, but only in included/required files:

function shutdown() {
        $isError = false;
        if($error = error_get_last()){
            switch($error['type']){
                case E_ERROR:
                case E_CORE_ERROR:
                case E_COMPILE_ERROR:
                case E_USER_ERROR:
                case E_PARSE:
                    $isError = true;
                    break;
            }
        }
        if ($isError){
            echo "Script execution halted ({$error['message']})";
        }
        else {
            echo "Script completed";
        }
}


register_shutdown_function('shutdown');

require 'broken.php'; // File with parse error

Notice I added E_PARSE constant to your switch(), this is the error you get.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.