【问题标题】:Php, how to cast/convert Exception to RuntimeException?Php,如何将异常转换/转换为 RuntimeException?
【发布时间】:2023-02-24 02:50:50
【问题描述】:

有一个代码sn-p:

function test()
{
    if (mt_rand(1,4) === 2)
    {
        throw new \Exception('exception');
    }
}

try
{
    test();
}
catch(\Exception $e)
{
    //throw $e;
    throw new \RuntimeException($e->getMessage());
}

这当然是一个微不足道的例子,但我有一个 test() 函数在两个项目中使用。其中之一可能会抛出异常并被处理。但在另一种情况下,我不能处理它,而是让它发生,我可以处理堆栈。

但是如果我使用 throw new \RuntimeException($e->getMessage()); 形式,我不会得到真正的堆栈跟踪,我不知道那是否发生在 test() 函数中。

但是,如果我使用 throw $e; 形式,它是 \Exception 而不是 RuntimeException

通常,Exception 是必须捕获的常见异常。但是一定不能捕获 RuntimeException,因为它可以在代码中解决。那么如何使 RuntimeException 异常呢?

【问题讨论】:

  • throw new \RuntimeException($e->getMessage(), $e->getCode(), $e);

标签: php exception


【解决方案1】:

请记住,RuntimeException 在其 constructor 中有一个可用的 $previous 参数,您可以在其中提供原始异常:

try {
    test();
} catch (Exception $e) {
    throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}

如果不需要,您也可以省略代码甚至消息:

throw new RuntimeException($e->getMessage(), previous: $e);
throw new RuntimeException(previous: $e);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2013-10-20
    • 2011-06-02
    • 2017-09-19
    • 2016-12-15
    • 2010-09-10
    • 1970-01-01
    相关资源
    最近更新 更多