dousong4777 2015-06-22 13:56
浏览 40
已采纳

register_shutdown_function捕获致命错误并更新json_encode

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条回答 默认 最新

  • duanmuybrtg1231 2015-06-22 14:02
    关注

    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);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)