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

前端 未结 17 2301
北荒
北荒 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 07:04

    PHP has catchable fatal errors. They are defined as E_RECOVERABLE_ERROR. The PHP manual describes an E_RECOVERABLE_ERROR as:

    Catchable fatal error. It indicates that a probably dangerous error occured, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR.

    You can "catch" these "fatal" errors by using set_error_handler() and checking for E_RECOVERABLE_ERROR. I find it useful to throw an Exception when this error is caught, then you can use try/catch.

    This question and answer provides a useful example: How can I catch a "catchable fatal error" on PHP type hinting?

    E_ERROR errors, however, can be handled, but not recovered from as the engine is in an unstable state.

提交回复
热议问题