捕获异常,设置上一个,重新抛出 [英] Catch Exception, set previous, re-throw

查看:103
本文介绍了捕获异常,设置上一个,重新抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码首先通过UDP发送消息,如果消息被截断,它将引发异常并通过TCP重试.如果那个调用生成异常,我想抛出两个 异常,以表示代码失败的确切方式.

I've got a bit of code that sends a message first over UDP, and if the message is truncated it raises an exception and retries over TCP. If that call generates an exception I would like to throw both exceptions to denote the exact manner in which the code has failed.

理想情况下,我会接受第二个异常并将其$previous设置为第一个异常,然后像这样重新抛出:

Ideally I would take the second exception and set its $previous to the first exception and re-throw like so:

try {
    $this->sendQueryUDP($packet);
    return $this->getResponseUDP($packet->getID());
} catch(TruncatedUDPPacketException $u) {
    try {
        return $this->sendQueryTCP($packet);
    } catch(\Exception $t) {
        $t->setPrevious($u); // this function doesn't exist!
        throw $t;
    }
}

但是,我看到的唯一设置$previous的方法是在Exception的构造函数中.

However, the only way I can see to set $previous is in Exception's constructor.

是否有更好的方法来实现这一目标?

Is there a better way to accomplish this?

推荐答案

我不会叫这个更好,但这是一种实现方法:

I wouldn't call this better, but here is a way to do it:

private function setPreviousException($e, $prev) {
    $reflection = new ReflectionClass($e);
    $prop = $reflection->getProperty('previous');
    $prop->setAccessible(true);
    $prop->setValue($e, $prev);
    $prop->setAccessible(false);
    return $e;
}

然后

try {
    $this->sendQueryUDP($packet);
    return $this->getResponseUDP($packet->getID());
} catch(TruncatedUDPPacketException $u) {
    try {
        return $this->sendQueryTCP($packet);
    } catch(\Exception $t) {
        $this->setPreviousException($t, $u);
        throw $t;
    }
}

这篇关于捕获异常,设置上一个,重新抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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