如何捕获所有 PHP 错误?
我需要一个解决方案来捕获所有 PHP 致命错误、异常、警告等并进行回调。
我想向用户显示错误的友好版本并记录该错误。
我正在考虑每天使用一个文本文件来记录错误。
有什么建议或 PHP 类(库)吗?
I need a solution to catch all PHP fatal errors, exceptions, warnings, etc. and have a callback.
I want to display a friendly version of the error to the user and log that error.
I'm thinking about using a text file per day for logging error.
Any suggestion or PHP class (library)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
从 PHP 8 开始,捕获所有异常的最佳方法是捕获 Throwable< /a> 接口“是可以通过 throw 语句抛出的任何对象的基本接口”。所以你的代码看起来像这样。
As of PHP 8 the best way to catch any and all Exceptions is to catch the Throwable interface which "is the base interface for any object that can be thrown via a throw statement". So your code would look something like this.
这使得几乎所有错误都成为
ErrorException
的可捕获实例:在可能给出错误的代码之前使用它,例如在 php 文件的最顶部或包含
Limits< 的 公共标头中的实例/em>: 无法使用用户定义的函数处理严重错误(PHP 引擎、服务器、语法):
E_ERROR
、E_PARSE
、E_CORE_ERROR
、E_CORE_WARNING
、E_COMPILE_ERROR
、E_COMPILE_WARNING
以及文件中引发的大部分E_STRICT
内容set_error_handler()被调用妥协了。但是,如果语法正确并且服务器没有损坏,则不应出现这些错误。
如果需要,您可以使用
register_shutdown_function()
和error_get_last()
解决此问题This makes almost all errors become catchable instance of
ErrorException
:use it before of the code that can give errors, for instances at the very top of your php file or in a common header included
Limits: Severest errors (PHP engine, server, syntax) cannot be handled with a user defined function:
E_ERROR
,E_PARSE
,E_CORE_ERROR
,E_CORE_WARNING
,E_COMPILE_ERROR
,E_COMPILE_WARNING
, and most ofE_STRICT
raised in the file where set_error_handler() is called compromise it.But, if syntax is correct and server don't broke, these errors should not appear.
If needed, you could workaround it with the
register_shutdown_function()
anderror_get_last()
php 方法: set_error_handler 可能就是您正在寻找的。
更多信息请参见: http://www.php.net/manual/ en/function.set-error-handler.php
和: http:// /php.net/manual/en/book.errorfunc.php
php method: set_error_handler might be what you are looking for.
More at: http://www.php.net/manual/en/function.set-error-handler.php
and at: http://php.net/manual/en/book.errorfunc.php
尝试启动此网页,您应该看到“消息:除以零”。
Try launch this web page, you should see "Message: Division by Zero".
我非常喜欢 kohana 框架的错误处理。不过,您必须做一些工作才能将其拉出来。
http://kohanaframework.org/
它将允许您将错误记录到文件并向收件人发送电子邮件。它还使您能够重定向到友好的错误页面。
I quite like the error handling from the kohana framework. You'd have to do a bit of work to pull it out though.
http://kohanaframework.org/
It will allow you to do error logging to a file and email a recipient. It also enables you to redirect to your friendly error page.