PHP: How to manage errors gracefully?

后端 未结 2 1268
南旧
南旧 2021-01-20 07:44

When failed to access something on the web (api, database), how would I stop executing the rest of the script and log the error in the log file? Well, and so that the visito

2条回答
  •  有刺的猬
    2021-01-20 08:11

    I generally like using Exceptions, in that kind of situation : it allows me to have all error-handling code at one place.


    For instance, I'd use something a bit like this :

    try {
        // Some code
    
        // Some code that throws an exception
    
        // Some other code -- will not be executed when there's been an Exception
    
    } catch (Exception $e) {
        // Log the technical error to file / database
    
        // Display a nice error message
    }
    

    With that, all error-handling code is in the catch block -- and not scatterred accros my whole application.


    Note, though, that many PHP functions don't throw exceptions, and only raise a warning or an error...

    For those, you could use set_error_handler to define your own error handler -- which could throw an Exception ;-)
    For instance, see the example on the manual page of ErrorException.

    Although this will work real fine for many errors/warnings, you should note that it will not work for Parse Error nor Fatal Error :

    • The first kind are actually raised before the PHP code is actually executed
    • And the second kind are... well... Fatal.


    And I would never place any die nor exit in the middle of my code : that's, in my opinion, one of the worst possible way of dealing with errors.

    I would also configure my server / application so :

    • Error messages are not displayed in the output, setting display_errors to Off.
    • Errors are logged to a file, using log_errors and error_log.

提交回复
热议问题