PHP:如何正确地管理错误? [英] PHP: How to manage errors gracefully?

查看:123
本文介绍了PHP:如何正确地管理错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果无法访问Web(api,数据库)上的某些内容,我将如何停止执行脚本的其余部分并将错误记录在日志文件中?那么访问者就不会看到确切的原因,而是看到我的自定义消息(比如说'坏事刚刚发生')。我需要采取哪些步骤安排事情?

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 visitor wouldn't see the exact cause but rather they would see my custom message (say, 'A bad thing just happened'). What steps do I need to take to arrange things?

推荐答案

我一般喜欢使用异常,在这种情况下:它允许我在一个地方拥有所有错误处理代码。

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
}

因此,所有错误处理代码都在 catch 阻止 - 而不是分散我的整个应用程序。

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



请注意,许多PHP函数不抛出异常,只会引发一个warnin g或错误...


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

对于那些,您可以使用 set_error_handler 来定义自己的错误处理程序 - 这可能会抛出异常;-)

例如, 手册页 ErrorException

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 :


  • PHP代码实际上是执行

  • 而第二种是...很好...致命的



我永远不会在中间放置任何 die exit 我的代码:那就是在我看来,处理错误的最糟糕的方法之一。


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.

我也会配置我的服务器ver / application so:

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.

这篇关于PHP:如何正确地管理错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆