How do I catch a PHP fatal (`E_ERROR`) error?

前端 未结 17 2568
北荒
北荒 2020-11-21 06:21

I can use set_error_handler() to catch most PHP errors, but it doesn\'t work for fatal (E_ERROR) errors, such as calling a function that doesn\'t e

17条回答
  •  孤城傲影
    2020-11-21 06:49

    Since most answers here are unnecesarily verbose, here's my non-ugly version of the top voted answer:

    function errorHandler($errno, $errstr, $errfile = '', $errline = 0, $errcontext = array()) {
        //Do stuff: mail, log, etc
    }
    
    function fatalHandler() {
        $error = error_get_last();
        if($error) errorHandler($error["type"], $error["message"], $error["file"], $error["line"]);
    }
    
    set_error_handler("errorHandler")
    register_shutdown_function("fatalHandler");
    

提交回复
热议问题