首页 文章

Laravel 5.2 - 未定义路由的默认错误页面

提问于
浏览
0

假设我在routes.php中有这个:

Route::get('sells', ['as' => 'user_sells', 'uses' => 'SellsController@indexAll']);

现在,如您所知,如果有人打开mySite.com/sells,则会执行控制器中所需的方法 .

但是,如果有人试图访问一个根本没有定义的路线,比如mySite.com/buys,我想显示一个默认的错误页面 . 我的意思是,我需要说明一个路线是否未定义,显示一个特定的页面 .

我怎样才能做到这一点?

提前致谢

Added: 我尝试访问未定义路由时遇到的错误:

哎呀,看起来出了问题 . C:\ wamp \ www \ codes \ laravel5 \ portpapa \ vendor \ laravel \ framework \ src \ Illuminate \ Container \ Container.php中的ErrorException行835:类Illuminate \ Routing中无法解析的依赖项解析[Parameter#0 [$ methods]] \ Route(查看:...

2 回答

  • 3

    实际上,Laravel默认已经有了这个 . 如果在 resources/views 文件夹中创建名为 errors/404.blade.php 的视图,则这将是自动的 .

    如果要使用自定义代码处理404错误,只需捕获 App\Exceptions\Handler 类中的 NotFoundHttpException 异常:

    public function render($request, Exception $e)
    {
        if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
            // handle here
            return response()->view('errors.404', [], 404);
        }
    }
    
  • 3

    如果未定义路由,则将抛出NotFoundHttpException . 异常在Larevel中以app / Exceptions / handler.php进行管理 .

    您必须检查异常是否为 NotFoundHttpException ,在这种情况下,返回正确的视图 .

    public function render($request, Exception $e)
    {
        if ($this->isHttpException($e))
        {       
            if($e instanceof NotFoundHttpException)
            {
                return response()->view('my.view', [], 404);
            }
            return $this->renderHttpException($e);
        }
        return parent::render($request, $e);
    }
    

    Source .

相关问题