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

前端 未结 17 2683
北荒
北荒 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:52

    There are certain circumstances in which even fatal errors should be caught (you might need to do some clean up before exiting gracefully and don’t just die..).

    I have implemented a pre_system hook in my CodeIgniter applications so that I can get my fatal errors through emails, and this helped me finding bugs that were not reported (or were reported after they were fixed, as I already knew about them :)).

    Sendemail checks if the error has already been reported so that it does not spam you with known errors multiple times.

    class PHPFatalError {
    
        public function setHandler() {
            register_shutdown_function('handleShutdown');
        }
    }
    
    function handleShutdown() {
        if (($error = error_get_last())) {
            ob_start();
            echo "
    ";
            var_dump($error);
            echo "
    "; $message = ob_get_clean(); sendEmail($message); ob_start(); echo '{"status":"error","message":"Internal application error!"}'; ob_flush(); exit(); } }

提交回复
热议问题