【问题标题】:Catching a NotFoundHttpException in the web.php file of Laravel 5.4 and throwing a custom exception在 Laravel 5.4 的 web.php 文件中捕获 NotFoundHttpException 并抛出自定义异常
【发布时间】:2018-01-27 04:20:06
【问题描述】:

当找不到路由时,我正在尝试找到一种自定义 Laravel 5.4 错误处理的方法。 在我的 web.php 中有一条路径定义不正确(故意用于测试目的)。我已经将它包装在一个 try...catch 块中并抛出了我自己的自定义异常 RoutesException:

try {
    Route::get('terms_rop_labels/view', 'LRChildController@view');
}catch (NotFoundHttpException $ex) {
    throw new RoutesException('terms_rop_labels/view');
}

然后在 app\Exceptions\Handler.php 我试图在测试视图中捕获异常:

if ($exception instanceof NotFoundHttpException) {
$parameters = [
'message'=> 'NotFoundHttpException'
];
return response()->view('errors.test', $parameters, 500);
}
if ($exception instanceof RoutesException) {
        $parameters = [
            'message'=> 'RoutesException'
        ];
        return response()->view('errors.test', $parameters, 500);
}

谁能解释为什么处理程序会捕获 NotFoundHttpException 而不是我的自定义 RoutesException?

【问题讨论】:

    标签: php laravel-5.4


    【解决方案1】:

    web.php 中的路由没有抛出 NotFoundHttpException 异常。您只是在 web.php 中注册路由,而不是解析它们。

    web.php 中的 Route 外观让您可以静态访问 Illuminate\Routing\Router 类中的 get 方法(参见 https://github.com/laravel/framework/blob/5.4/src/Illuminate/Routing/Router.php 中的第 125 - 135 行)

    /**
     * Register a new GET route with the router.
     *
     * @param  string  $uri
     * @param  \Closure|array|string|null  $action
     * @return \Illuminate\Routing\Route
     */
    public function get($uri, $action = null)
    {
        return $this->addRoute(['GET', 'HEAD'], $uri, $action);
    }
    

    (所以您只是在 web.php 文件中使用 Router get 方法将路由添加到 RouteCollection。)

    如果您查看回溯,您可以看到在您的案例中引发 NotFoundHttpException 异常的位置。例如,如果您通过在 web.php 中注册来导航到尚未添加到路由集合中的不存在的路由,您会看到第 179 行的 RouteCollection 类匹配方法正在抛出 NotFoundHttpException。

    在你的情况下,try/catch 没有捕获 NotFoundHttpException 因为

    Route::get('terms_rop_labels/view', 'LRChildController@view');
    

    没有抛出 NotFoundHttpException。

    也许你可以通过在 app\Exceptions\Handler 中捕获 NotFoundHttpException 来实现你想要的。

    【讨论】:

      猜你喜欢
      • 2015-07-14
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-08
      相关资源
      最近更新 更多