How to catch a PHP fatal (E_ERROR) error?

Spread the love

Sometimes, we want to catch a PHP fatal (E_ERROR) error.

In this article, we’ll look at how to catch a PHP fatal (E_ERROR) error.

How to catch a PHP fatal (E_ERROR) error?

To catch a PHP fatal (E_ERROR) error, we can use the register_shutdown_function function.

For instance, we write

register_shutdown_function("fatal_handler");

function fatal_handler() {
    $errfile = "unknown file";
    $errstr  = "shutdown";
    $errno   = E_CORE_ERROR;
    $errline = 0;

    $error = error_get_last();

    if($error !== NULL) {
        $errno   = $error["type"];
        $errfile = $error["file"];
        $errline = $error["line"];
        $errstr  = $error["message"];
        //...        
    }
}

to call register_shutdown_function with the 'fatal_handler' function name string to use fatal_handler as the error handler for fatal errors.

In fatal_handler, we get the error object with error_get_last.

And then we get trhe values from the associative array returned.

Then we can do what we want with the values.

$error["type"] has the error type as a number.

$error["file"] has the file that raised the error.

$error["line"] has the line that caused the error.

$error["message"] has the error message.

Conclusion

To catch a PHP fatal (E_ERROR) error, we can use the register_shutdown_function function.

Leave a Reply

Your email address will not be published.