在异常处理程序中抛出异常

Bra*_*rad 11 php error-handling exception-handling exception

我有一个带有异常处理程序的脚本.在异常之后脚本退出之前,此异常处理程序会清除几个连接.

我想从这个异常处理程序中重新抛出异常,以便它由PHP自己的最后一个异常处理程序处理,其中错误被写入PHP的错误日志,或者PHP.ini中配置的默认错误日志.

不幸的是,这似乎不太可能,如下所述:

http://www.php.net/manual/en/function.set-exception-handler.php#68712

将导致致命错误:抛出没有堆栈帧的异常

是否有另一种方法可以将错误冒充堆栈,以便PHP在我的异常处理程序清理完成后处理它?

hak*_*kre 16

您无法从异常处理程序中重新抛出,但是,您可以使用其他位置.例如,您可以通过将事物封装到自己的类中来解除对处理程序的重新抛出,然后使用该__destruct()函数(PHP 5.3,Demo):

<?php

class ExceptionHandler
{
    private $rethrow;
    public function __construct()
    {
        set_exception_handler(array($this, 'handler'));
    }
    public function handler($exception)
    {
        echo  "cleaning up.\n";
        $this->rethrow = $exception;
    }
    public function __destruct()
    {
        if ($this->rethrow) throw $this->rethrow;
    }
}

$handler = new ExceptionHandler;

throw new Exception();
Run Code Online (Sandbox Code Playgroud)

把它放到我的错误日志中:

[29-Oct-2011 xx:32:25] PHP Fatal error: Uncaught exception 'Exception' in /.../test-exception.php:23
Stack trace:
#0 {main}
thrown in /.../test-exception.php on line 23
Run Code Online (Sandbox Code Playgroud)


Mik*_*ell 8

只需捕获异常并自行记录消息,然后重新抛出.

try {
    $foo->doSomethingToCauseException();
} catch (Exception $e) {
    error_log($e->getMessage());
    throw $e;
}
Run Code Online (Sandbox Code Playgroud)

如果冒泡到顶部并且PHP无法处理,则会导致未捕获的异常.