Fatal error catched by register_shutdown_function and update json_encode

596 views Asked by At

I can catch a fatal error with register_shutdown_function('shutdown')

function shutdown(){
    $error = error_get_last();
    $result['message'] = $error['message'];
}

and I have an echo json_encode($result);

Unfortunately this echo json_encode shows nothing because json is not updated with the message of the fatal error.

What can I do to fix this?

1

There are 1 answers

3
RiggsFolly On BEST ANSWER

Why move one array to another array and then echo the second array.

Why not just do this

function shutdown(){
    $error = error_get_last();
    echo json_encode($error);
}

Or even this

function shutdown(){
    echo json_encode(error_get_last());
}

Apart form the use of an unnecessary array, this will give you all the information available from get_last_error()

Of course it could be that the error_get_last() information is just not available at this late stage in the shutdown process. If this is the case then you can pass extra parameters to the shutdown function and this may be what you need to do.

register_shutdown_function('shutdown', get_last_error());

and

function shutdown($last_error){
    echo json_encode($last_error);
}

EDITED:

First I have added error_reporting(~E_ERROR); // don't report fatal errors

The first one worked for me I mean

error_reporting(~E_ERROR); // don't report fatal 

register_shutdown_function('shutdown');

function shutdown(){
    $error = error_get_last();

    if ($error['type'] === 1){ 
         echo json_encode($error);
}

For my needs I wrote:

function shutdown(){
    $error = error_get_last();

    if ($error['type'] === 1){ // 1 means fatal error
         $res['message'] = $error['message'];

         $res['success'] = true;

         header('Content-Type: application/json');

         echo json_encode($res);
    }
}