php 如何捕获所有php错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4514568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to catch all php error
提问by StoneHeart
I need a solution to catch all php fatal errors, exceptions, warnings etc...and give a callback. So I can display a friendly version to user and log that error. About logging method. My php script allow many sites running with a single installation. I think I will use text file for each day. Any sugesstion or php class, lib?
我需要一个解决方案来捕获所有 php 致命错误、异常、警告等......并提供回调。所以我可以向用户显示一个友好的版本并记录该错误。关于记录方法。我的 php 脚本允许通过一次安装运行多个站点。我想我每天都会使用文本文件。任何 sugesstion 或 php 类,lib?
回答by Andreas
php method: set_error_handlermight be what you are looking for.
php 方法:set_error_handler可能就是你要找的。
More at: http://www.php.net/manual/en/function.set-error-handler.php
更多信息:http: //www.php.net/manual/en/function.set-error-handler.php
回答by Luca C.
This makes almost all errors become catchable instance of ErrorException
:
这使得几乎所有错误都成为可捕获的实例ErrorException
:
set_error_handler(function($errno, $errstr, $errfile, $errline ){
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});
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
在可能出错的代码之前使用它,例如在 php 文件的最顶部或包含的公共标头中
Limits: Severesterrors (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 of E_STRICT
raised in the file where set_error_handler() is called compromise it.
限制:病犬错误(PHP引擎,服务器,语法)不能与用户定义的函数来处理:E_ERROR
,E_PARSE
,E_CORE_ERROR
,E_CORE_WARNING
,E_COMPILE_ERROR
,E_COMPILE_WARNING
,大部分E_STRICT
地方的set_error_han dler()被调用妥协它在文件中提出的。
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()
and error_get_last()
如果需要,您可以使用register_shutdown_function()
和解决它error_get_last()
回答by BR1COP
Try launch this web page, you should see "Message: Division by Zero".
尝试启动此网页,您应该会看到“消息:除以零”。
// Set Error Handler
set_error_handler (
function($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
);
// Trigger an exception in a try block
try {
$a = 3/0;
echo $a;
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
回答by Jason
I quite like the error handling from the kohana framework. You'd have to do a bit of work to pull it out though.
我非常喜欢 kohana 框架的错误处理。你必须做一些工作才能把它拉出来。
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.
它将允许您将错误记录到文件并通过电子邮件发送给收件人。它还使您能够重定向到友好的错误页面。