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

前端 未结 17 2304
北荒
北荒 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 06:53

    Fatal errors or recoverable fatal errors now throw instances of Error in PHP 7 or higher versions. Like any other exceptions, Error objects can be caught using a try/catch block.

    Example:

    method(); // Throws an Error object in PHP 7 or higger.
    } catch (Error $e) {
        // Handle error
        echo $e->getMessage(); // Call to a member function method() on string
    }
    

    https://3v4l.org/67vbk

    Or you can use Throwable interface to catch all exceptions.

    Example:

    getMessage(); // Call to undefined function undefinedFunctionCall()
        }
    

    https://3v4l.org/Br0MG

    For more information: http://php.net/manual/en/language.errors.php7.php

提交回复
热议问题