抓住一个异常,抛出另一个..还有其他办法吗


catch an exception an throw another one... is there any other way?

在Laravel框架中,每当您尝试从雄辩的模型中获取一些数据时,如果发生异常,它都会抛出ModelNotFoundException。在我的项目中,我需要捕获此异常并将用户重定向到特定路由。

我最终得到的解决方案是这样的:

try{
        $foundUser = $this->user->whereId($id)->firstOrFail();
    }catch(ModelNotFoundException $e){
        throw new NonExistantUserException;
    }

我知道我可以将我的重定向代码放在 catch 块中,但是我已经在全局中捕获了这些异常.php:

App::error(function(NonExistantUserException $e)
{
    return Redirect::back()->WithInput();
});

我想知道有什么办法可以说,例如,无论 try 块内发生什么样的异常,我都想NonExistantUserException只针对这个 try 块捕获它!

我问是因为抓住一个异常会抛出另一个异常。 对我来说似乎是一种不好的做法。

提前谢谢。

绝对不是坏做法,甚至是常见的做法。但是,您不应简单地丢弃以前的异常,因为它可能对调试目的很有用。

<?php
try {
    $foundUser = $this->user->whereId($id)->firstOrFail();
} catch (ModelNotFoundException $e) {
    throw new NonExistentUserException(
        "Could not find user for '{$id}'.",
        null,
        $e // Keep previous exception.
    );
}

这可确保您拥有完整的异常链。除此之外,你的方法对我来说很好。

相关文章: