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

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

    Well, it seems possible to catch fatal errors some other way :)

    ob_start('fatal_error_handler');
    
    function fatal_error_handler($buffer){
        $error = error_get_last();
        if($error['type'] == 1){
            // Type, message, file, line
            $newBuffer='<html><header><title>Fatal Error </title></header>
                          <style>
                        .error_content{
                            background: ghostwhite;
                            vertical-align: middle;
                            margin:0 auto;
                            padding: 10px;
                            width: 50%;
                         }
                         .error_content label{color: red;font-family: Georgia;font-size: 16pt;font-style: italic;}
                         .error_content ul li{ background: none repeat scroll 0 0 FloralWhite;
                                    border: 1px solid AliceBlue;
                                    display: block;
                                    font-family: monospace;
                                    padding: 2%;
                                    text-align: left;
                          }
                          </style>
                          <body style="text-align: center;">
                            <div class="error_content">
                                 <label >Fatal Error </label>
                                 <ul>
                                   <li><b>Line</b> ' . $error['line'] . '</li>
                                   <li><b>Message</b> ' . $error['message'] . '</li>
                                   <li><b>File</b> ' . $error['file'] . '</li>
                                 </ul>
    
                                 <a href="javascript:history.back()"> Back </a>
                            </div>
                          </body></html>';
    
            return $newBuffer;
        }
        return $buffer;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-21 07:06

    PHP doesn't provide conventional means for catching and recovering from fatal errors. This is because processing should not typically be recovered after a fatal error. String matching an output buffer (as suggested by the original post the technique described on PHP.net) is definitely ill-advised. It's simply unreliable.

    Calling the mail() function from within an error handler method prove to be problematic, too. If you had a lot of errors, your mail server would be loaded with work, and you could find yourself with a gnarly inbox. To avoid this, you might consider running a cron to scan error logs periodically and send notifications accordingly. You might also like to look into system monitoring software, such as Nagios.


    To speak to the bit about registering a shutdown function:

    It's true that you can register a shutdown function, and that's a good answer.

    The point here is that we typically shouldn't try to recover from fatal errors, especially not by using a regular expression against your output buffer. I was responding to the accepted answer, which linked to a suggestion on php.net which has since been changed or removed.

    That suggestion was to use a regex against the output buffer during exception handling, and in the case of a fatal error (detected by the matching against whatever configured error text you might be expecting), try to do some sort of recovery or continued processing. That would not be a recommended practice (I believe that's why I can't find the original suggestion, too. I'm either overlooking it, or the php community shot it down).

    It might be worth noting that the more recent versions of PHP (around 5.1) seem to call the shutdown function earlier, before the output buffering callback is envoked. In version 5 and earlier, that order was the reverse (the output buffering callback was followed by the shutdown function). Also, since about 5.0.5 (which is much earlier than the questioner's version 5.2.3), objects are unloaded well before a registered shutdown function is called, so you won't be able to rely on your in-memory objects to do much of anything.

    So registering a shutdown function is fine, but the sort of tasks that ought to be performed by a shutdown function are probably limited to a handful of gentle shutdown procedures.

    The key take-away here is just some words of wisdom for anyone who stumbles upon this question and sees the advice in the originally accepted answer. Don't regex your output buffer.

    0 讨论(0)
  • 2020-11-21 07:07

    I just came up with this solution (PHP 5.2.0+):

    function shutDownFunction() {
        $error = error_get_last();
         // Fatal error, E_ERROR === 1
        if ($error['type'] === E_ERROR) {
             // Do your stuff
        }
    }
    register_shutdown_function('shutDownFunction');
    

    Different error types are defined at Predefined Constants.

    0 讨论(0)
  • 2020-11-21 07:12

    I need to handle fatal errors for production to instead show a static styled 503 Service Unavailable HTML output. This is surely a reasonable approach to "catching fatal errors". This is what I've done:

    I have a custom error handling function "error_handler" which will display my "503 service unavailable" HTML page on any E_ERROR, E_USER_ERROR, etc. This will now be called on the shutdown function, catching my fatal error,

    function fatal_error_handler() {
    
        if (@is_array($e = @error_get_last())) {
            $code = isset($e['type']) ? $e['type'] : 0;
            $msg = isset($e['message']) ? $e['message'] : '';
            $file = isset($e['file']) ? $e['file'] : '';
            $line = isset($e['line']) ? $e['line'] : '';
            if ($code>0)
                error_handler($code, $msg, $file, $line);
        }
    }
    set_error_handler("error_handler");
    register_shutdown_function('fatal_error_handler');
    

    in my custom error_handler function, if the error is E_ERROR, E_USER_ERROR, etc. I also call @ob_end_clean(); to empty the buffer, thus removing PHP's "fatal error" message.

    Take important note of the strict isset() checking and @ silencing functions since we don’t want our error_handler scripts to generate any errors.

    In still agreeing with keparo, catching fatal errors does defeat the purpose of "FATAL error" so it's not really intended for you to do further processing. Do not run any mail() functions in this shutdown process as you will certainly back up the mail server or your inbox. Rather log these occurrences to file and schedule a cron job to find these error.log files and mail them to administrators.

    0 讨论(0)
提交回复
热议问题