在异常处理程序中抛出异常 [英] Throwing exception within exception handler

查看:121
本文介绍了在异常处理程序中抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有异常处理程序的脚本。这个异常处理程序可以在异常之前退出脚本之前清除几个连接。



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



不幸的是,这似乎不像这样概述:



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


将导致致命错误:没有堆栈框架抛出异常


有没有另外一种方式来将错误提升到堆栈中,以便在我的异常处理程序完成清理后PHP处理它?<​​/ p>

解决方案

你不能从异常手中重新抛出但是,还有其他的地方你可以。例如,您可以通过将事情封装到一个自己的类中,从处理程序中解决重新抛出,然后使用 __ destruct()函数(PHP 5.3,演示):

  ;?php 

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

$ handler = new ExceptionHandler;

抛出新的异常();

将其放入我的错误日志中:

  [2011年10月29日xx:32:25] PHP致命错误:/.../test-exception.php:23中的未捕获异常异常
堆栈跟踪:
#0 {main}
抛出在/.../test-exception.php第23行


I have a script with an exception handler. This exception handler cleans up a couple connections, prior to the script exiting after an exception.

I would like to re-throw the exception from this exception handler so that it is handled by PHP's own last-resort exception handler, where the error is written to PHP's error log, or whatever the default is, as configured in PHP.ini.

Unfortunately, this doesn't seem like a possibility, as outlined here:

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

Will cause a Fatal error: Exception thrown without a stack frame

Is there another way to bubble the error up the stack so that PHP handles it after my exception handler is done cleaning up?

解决方案

You can not re-throw from the exception handler, however, there are other places you can. For example you can de-couple the re-throw from the handler by encapsulating things into a class of it's own and then use the __destruct() function (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();

Put this into my error log:

[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

这篇关于在异常处理程序中抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆