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.

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

报告相同问题?

悬赏问题

  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决
  • ¥15 关于华为5g模块mh5000-31接线问题
  • ¥15 keil L6007U报错
  • ¥15 webapi 发布到iis后无法访问