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 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备