PHP中的错误处理 [英] Error handling in PHP

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

问题描述

我熟悉一些基础知识,但是我想更多地了解的是什么时候和为什么在PHP中使用错误处理(包括抛出异常),特别是在实时站点或Web应用程序上。是否可以过度使用,如果是,过度使用的样子是什么?有没有不应该使用的情况?另外,有关错误处理的常见安全问题是什么?

I'm familiar with some of the basics, but what I would like to know more about is when and why error handling (including throwing exceptions) should be used in PHP, especially on a live site or web app. Is it something that can be overused and if so, what does overuse look like? Are there cases where it shouldn't be used? Also, what are some of the common security concerns in regard to error handling?

推荐答案

有一件事要补充说最重要的是,您将Web应用程序中的任何错误记录到日志中。这样,正如杰夫编码恐怖Atwood所说,你会知道你的用户在你的应用程序遇到什么问题(而不是问他们是什么问题)。

One thing to add to what was said already is that it's paramount that you record any errors in your web application into a log. This way, as Jeff "Coding Horror" Atwood suggests, you'll know when your users are experiencing trouble with your app (instead of "asking them what's wrong").

为此,我建议您使用以下类型的基础架构:

To do this, I recommend the following type of infrastructure:


  • 创建数据库中的崩溃表和一组报告错误的包装类。我建议为崩溃设置类别(阻止,安全,PHP错误/警告(vs异常)等)。

  • 在所有错误处理代码中,确保记录错误。这样做一定取决于你如何构建API(上面的步骤) - 它应该是琐碎的来记录崩溃,如果做到正确。

  • Create a "crash" table in your database and a set of wrapper classes for reporting errors. I'd recommend setting categories for the crashes ("blocking", "security", "PHP error/warning" (vs exception), etc).
  • In all of your error handling code, make sure to record the error. Doing this consistently depends on how well you built the API (above step) - it should be trivial to record crashes if done right.

额外的功劳:有时您的崩溃将是数据库级崩溃:即DB服务器关闭等。如果是这样,您的错误日志记录基础设施(上)将失败(您不能将崩溃记录到数据库,因为日志会尝试写入数据库)。在这种情况下,我将在崩溃包装器类中写入故障切换逻辑,以将

Extra credit: sometimes, your crashes will be database-level crashes: i.e. DB server down, etc. If that's the case, your error logging infrastructure (above) will fail (you can't log the crash to the DB because the log tries to write to the DB). In that case, I would write failover logic in your Crash wrapper class to either


  • 向管理员发送电子邮件,AND / OR

  • 将崩溃的详细信息记录到纯文本文件

所有这一切听起来像一个过度的,但相信我,这是否会使您的申请被接受为稳定或片状。这种区别来自于所有应用程序始终都是片面/崩溃的事实,但是那些知道应用程序所有问题的开发人员都有机会实际修复它。

All of this sounds like an overkill, but believe me, this makes a difference in whether your application is accepted as a "stable" or "flaky". That difference comes from the fact that all apps start as flaky/crashing all the time, but those developers that know about all issues with their app have a chance to actually fix it.

这篇关于PHP中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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