我一般喜欢使用例外情况,在这种情况下:它允许我将所有错误处理代码放在一个地方。
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
块——并且没有分散在我的整个应用程序中。
Note, though, that many PHP functions don't throw exceptions, and only raise a warning or an error...
对于那些,你可以使用set_error_handler定义您自己的错误处理程序——这可能会抛出异常;-)
例如,请参阅上的示例的手册页ErrorException.
尽管这对于许多错误/警告来说效果很好,但您应该注意,它不适用于Parse Error
nor Fatal Error
:
- 第一种实际上是在 PHP 代码实际执行之前引发的
- 第二种是……嗯……致命的。
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.
我还会配置我的服务器/应用程序:
- 错误消息不显示在输出、设置中display_errors to
Off
.
- 错误被记录到文件中,使用log_errors and error_log.