我可以使用set_error_handler()来捕获大多数PHP错误,但它不适用于致命(E_ERROR)错误,例如调用不存在的函数。是否有其他方法来捕捉这些错误?
我试图调用mail()为所有错误和运行PHP 5.2.3。
我可以使用set_error_handler()来捕获大多数PHP错误,但它不适用于致命(E_ERROR)错误,例如调用不存在的函数。是否有其他方法来捕捉这些错误?
我试图调用mail()为所有错误和运行PHP 5.2.3。
当前回答
在Zend Framework 2中找到了很好的解决方案:
/**
* ErrorHandler that can be used to catch internal PHP errors
* and convert to an ErrorException instance.
*/
abstract class ErrorHandler
{
/**
* Active stack
*
* @var array
*/
protected static $stack = array();
/**
* Check if this error handler is active
*
* @return bool
*/
public static function started()
{
return (bool) static::getNestedLevel();
}
/**
* Get the current nested level
*
* @return int
*/
public static function getNestedLevel()
{
return count(static::$stack);
}
/**
* Starting the error handler
*
* @param int $errorLevel
*/
public static function start($errorLevel = \E_WARNING)
{
if (!static::$stack) {
set_error_handler(array(get_called_class(), 'addError'), $errorLevel);
}
static::$stack[] = null;
}
/**
* Stopping the error handler
*
* @param bool $throw Throw the ErrorException if any
* @return null|ErrorException
* @throws ErrorException If an error has been catched and $throw is true
*/
public static function stop($throw = false)
{
$errorException = null;
if (static::$stack) {
$errorException = array_pop(static::$stack);
if (!static::$stack) {
restore_error_handler();
}
if ($errorException && $throw) {
throw $errorException;
}
}
return $errorException;
}
/**
* Stop all active handler
*
* @return void
*/
public static function clean()
{
if (static::$stack) {
restore_error_handler();
}
static::$stack = array();
}
/**
* Add an error to the stack
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @return void
*/
public static function addError($errno, $errstr = '', $errfile = '', $errline = 0)
{
$stack = & static::$stack[count(static::$stack) - 1];
$stack = new ErrorException($errstr, 0, $errno, $errfile, $errline, $stack);
}
}
这个类允许您在需要时启动特定的ErrorHandler。然后你也可以停止处理程序。
使用这个类,例如:
ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();
if ($innerException = ErrorHandler::stop()) {
throw new Exception('Special Exception Text', 0, $innerException);
}
// or
ErrorHandler::stop(true); // directly throws an Exception;
链接到完整的类代码:https://github.com/zendframework/zf2/blob/master/library/Zend/Stdlib/ErrorHandler.php
一个更好的解决方案是独白: 链接到完整的类代码:https://github.com/Seldaek/monolog/blob/master/src/Monolog/ErrorHandler.php
它还可以使用register_shutdown_function函数处理FATAL_ERRORS。根据这个类,FATAL_ERROR是以下数组之一(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR)。
class ErrorHandler
{
// [...]
public function registerExceptionHandler($level = null, $callPrevious = true)
{
$prev = set_exception_handler(array($this, 'handleException'));
$this->uncaughtExceptionLevel = $level;
if ($callPrevious && $prev) {
$this->previousExceptionHandler = $prev;
}
}
public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
{
$prev = set_error_handler(array($this, 'handleError'), $errorTypes);
$this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
if ($callPrevious) {
$this->previousErrorHandler = $prev ?: true;
}
}
public function registerFatalHandler($level = null, $reservedMemorySize = 20)
{
register_shutdown_function(array($this, 'handleFatalError'));
$this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
$this->fatalLevel = $level;
}
// [...]
}
其他回答
由于这里的大多数答案都是不必要的啰嗦,下面是我投票最多的答案的不丑陋版本:
function errorHandler($errno, $errstr, $errfile = '', $errline = 0, $errcontext = array()) {
//Do stuff: mail, log, etc
}
function fatalHandler() {
$error = error_get_last();
if($error) errorHandler($error["type"], $error["message"], $error["file"], $error["line"]);
}
set_error_handler("errorHandler")
register_shutdown_function("fatalHandler");
如果使用PHP, >= 5.1.0 只需对errrexception类执行如下操作:
<?php
// Define an error handler
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
// Set your error handler
set_error_handler("exception_error_handler");
/* Trigger exception */
try
{
// Try to do something like finding the end of the internet
}
catch(ErrorException $e)
{
// Anything you want to do with $e
}
?>
好吧,似乎可以用其他方式捕获致命错误:)
ob_start('fatal_error_handler');
function fatal_error_handler($buffer){
$error = error_get_last();
if($error['type'] == 1){
// Type, message, file, line
$newBuffer='<html><header><title>Fatal Error </title></header>
<style>
.error_content{
background: ghostwhite;
vertical-align: middle;
margin:0 auto;
padding: 10px;
width: 50%;
}
.error_content label{color: red;font-family: Georgia;font-size: 16pt;font-style: italic;}
.error_content ul li{ background: none repeat scroll 0 0 FloralWhite;
border: 1px solid AliceBlue;
display: block;
font-family: monospace;
padding: 2%;
text-align: left;
}
</style>
<body style="text-align: center;">
<div class="error_content">
<label >Fatal Error </label>
<ul>
<li><b>Line</b> ' . $error['line'] . '</li>
<li><b>Message</b> ' . $error['message'] . '</li>
<li><b>File</b> ' . $error['file'] . '</li>
</ul>
<a href="javascript:history.back()"> Back </a>
</div>
</body></html>';
return $newBuffer;
}
return $buffer;
}
您不能捕获/处理致命错误,但可以记录/报告它们。 为了快速调试,我修改了这段简单代码的一个答案
function __fatalHandler()
{
$error = error_get_last();
// Check if it's a core/fatal error, otherwise it's a normal shutdown
if ($error !== NULL && in_array($error['type'],
array(E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING,
E_COMPILE_ERROR, E_COMPILE_WARNING,E_RECOVERABLE_ERROR))) {
echo "<pre>fatal error:\n";
print_r($error);
echo "</pre>";
die;
}
}
register_shutdown_function('__fatalHandler');
在Zend Framework 2中找到了很好的解决方案:
/**
* ErrorHandler that can be used to catch internal PHP errors
* and convert to an ErrorException instance.
*/
abstract class ErrorHandler
{
/**
* Active stack
*
* @var array
*/
protected static $stack = array();
/**
* Check if this error handler is active
*
* @return bool
*/
public static function started()
{
return (bool) static::getNestedLevel();
}
/**
* Get the current nested level
*
* @return int
*/
public static function getNestedLevel()
{
return count(static::$stack);
}
/**
* Starting the error handler
*
* @param int $errorLevel
*/
public static function start($errorLevel = \E_WARNING)
{
if (!static::$stack) {
set_error_handler(array(get_called_class(), 'addError'), $errorLevel);
}
static::$stack[] = null;
}
/**
* Stopping the error handler
*
* @param bool $throw Throw the ErrorException if any
* @return null|ErrorException
* @throws ErrorException If an error has been catched and $throw is true
*/
public static function stop($throw = false)
{
$errorException = null;
if (static::$stack) {
$errorException = array_pop(static::$stack);
if (!static::$stack) {
restore_error_handler();
}
if ($errorException && $throw) {
throw $errorException;
}
}
return $errorException;
}
/**
* Stop all active handler
*
* @return void
*/
public static function clean()
{
if (static::$stack) {
restore_error_handler();
}
static::$stack = array();
}
/**
* Add an error to the stack
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @return void
*/
public static function addError($errno, $errstr = '', $errfile = '', $errline = 0)
{
$stack = & static::$stack[count(static::$stack) - 1];
$stack = new ErrorException($errstr, 0, $errno, $errfile, $errline, $stack);
}
}
这个类允许您在需要时启动特定的ErrorHandler。然后你也可以停止处理程序。
使用这个类,例如:
ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();
if ($innerException = ErrorHandler::stop()) {
throw new Exception('Special Exception Text', 0, $innerException);
}
// or
ErrorHandler::stop(true); // directly throws an Exception;
链接到完整的类代码:https://github.com/zendframework/zf2/blob/master/library/Zend/Stdlib/ErrorHandler.php
一个更好的解决方案是独白: 链接到完整的类代码:https://github.com/Seldaek/monolog/blob/master/src/Monolog/ErrorHandler.php
它还可以使用register_shutdown_function函数处理FATAL_ERRORS。根据这个类,FATAL_ERROR是以下数组之一(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR)。
class ErrorHandler
{
// [...]
public function registerExceptionHandler($level = null, $callPrevious = true)
{
$prev = set_exception_handler(array($this, 'handleException'));
$this->uncaughtExceptionLevel = $level;
if ($callPrevious && $prev) {
$this->previousExceptionHandler = $prev;
}
}
public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
{
$prev = set_error_handler(array($this, 'handleError'), $errorTypes);
$this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
if ($callPrevious) {
$this->previousErrorHandler = $prev ?: true;
}
}
public function registerFatalHandler($level = null, $reservedMemorySize = 20)
{
register_shutdown_function(array($this, 'handleFatalError'));
$this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
$this->fatalLevel = $level;
}
// [...]
}