首页 PHP常见问题

PHP: 错误处理 函数

From: https://php.net/manual/zh/ref.errorfunc.php
PHP5 only (only tested with php5.0).

If you, for some reason, prefer exceptions over errors and have your custom error handler (set_error_handler) wrap the error into an exception you have to be careful with your script.

Because if you, instead of just calling the exception handler, throws the exception, and having a custom exception handler (set_exception_handler). And an error is being triggered inside that exception handler, you will get a weird error:
"Fatal error: Exception thrown without a stack frame in Unknown on line 0"

This error is not particulary informative, is it? :)

This example below will cause this error.
<?php
class PHPErrorException extends Exception
{
    private $context = null;
    public function __construct
        ($code, $message, $file, $line, $context = null)
    {
        parent::__construct($message, $code);
        $this->file = $file;
        $this->line = $line;
        $this->context = $context;
    }
};

function error_handler($code, $message, $file, $line) {
    throw new PHPErrorException($code, $message, $file, $line);
}

function exception_handler(Exception $e)
{   
    $errors = array(
        E_USER_ERROR        => "User Error",
        E_USER_WARNING        => "User Warning",
        E_USER_NOTICE        => "User Notice",
        );
       
    echo $errors[$e->getCode()].': '.$e->getMessage().' in '.$e->getFile().
        ' on line '.$e->getLine()."\n";
    echo $e->getTraceAsString();
}

set_error_handler('error_handler');
set_exception_handler('exception_handler');

// Throw exception with an /unkown/ error code.
throw new Exception('foo', 0);
?>

There are however, easy fix for this as it's only cause is sloppy code.
Like one, directly call exception_handler from error_handler instead of throwing an exception. Not only does it remedy this problem, but it's also faster. Though this will cause a `regular` unhandled exception being printed and if only "designed" error messages are intended, this is not the ultimate solution.

So, what is there to do? Make sure the code in exception_handlers doesn't cause any errors! In this case a simple isset() would have solved it.

regards, C-A B.