duanjia7912 2017-08-18 13:01
浏览 222
已采纳

在Laravel 5.4的web.php文件中捕获NotFoundHttpException并抛出自定义异常

I'm trying to find a way of customising the error handling of Laravel 5.4 when a route can't be found. In my web.php there is a route incorrectly defined (deliberately for testing purposes). I have wrapped it in a try...catch block and thrown my own custom exception RoutesException:

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

Then in app\Exceptions\Handler.php I am trying to catch the exception in a test view:

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);
}

Can anyone explain why the handler catches a NotFoundHttpException and not my custom RoutesException?

  • 写回答

1条回答 默认 最新

  • doupin2013 2017-08-18 14:18
    关注

    The route in web.php is not throwing a NotFoundHttpException exception. You are just registering routes in web.php, not resolving them.

    The Route facade in web.php is giving you static access to the get method in the Illuminate\Routing\Router class (see lines of 125 - 135 in https://github.com/laravel/framework/blob/5.4/src/Illuminate/Routing/Router.php)

    /**
     * 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);
    }
    

    (So you are just adding routes to the RouteCollection with Router get method in the web.php file.)

    If you look in the back-trace, you can see where the NotFoundHttpException exception is being thrown in your case. For example, if you were to navigate to a nonexistent route that you have not added to the route collection by registering it in web.php, you would see that the NotFoundHttpException is being thrown by the RouteCollection class match method on line 179.

    In your case, the try/catch in not catching a NotFoundHttpException because the

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

    is not throwing the NotFoundHttpException.

    Maybe you can achieve what you want by just catching NotFoundHttpException in the app\Exceptions\Handler instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置