PHP 中的错误处理

Error handling in PHP(PHP 中的错误处理)
本文介绍了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 应用程序中的任何错误记录到日志中是最重要的.这样,正如 Jeff Coding Horror" 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 错误/警告"(与异常)等).
  • 在您的所有错误处理代码中,确保记录错误.始终如一地执行此操作取决于您构建 API(上述步骤)的程度 - 如果操作正确,记录崩溃应该微不足道.

额外的功劳:有时,您的崩溃将是数据库级别的崩溃:即数据库服务器关闭等.如果是这种情况,您的错误记录基础架构(以上)将失败(您无法将崩溃记录到数据库中,因为日志尝试写入数据库).在这种情况下,我会在您的 Crash 包装器类中将故障转移逻辑编写为

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

  • 向管理员发送电子邮件,和/或
  • 将崩溃的详细信息记录到纯文本文件中

所有这些听起来都有些矫枉过正,但相信我,这会影响您的应用程序是被接受为稳定"还是不稳定".这种差异源于这样一个事实,即所有应用程序一开始都是不稳定/崩溃的,但那些了解其应用程序所有问题的开发人员有机会实际修复它.

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 中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)