假设我的routes.php:中有这个
Route::get('sells', ['as' => 'user_sells', 'uses' => 'SellsController@indexAll']);
现在,正如您所知,如果有人打开mySite.com/sells,控制器中所需的方法就会被执行。
但是,如果有人试图访问一个根本没有定义的路由,比如mySite.com/buys,我想显示一个默认的错误页面。我的意思是,我需要说的是,如果没有定义路线,显示一个特定的页面。
我该怎么做?
提前感谢
添加:当我试图访问未定义的路线时,我面临的错误:
哎呀,好像出了什么问题。
中的ErrorExceptionC: ''wamp''www''coodes''laravel5''portpapa''vendor''laravel''framework''src''Illuminate''Container.php第835行:无法解析的依赖项解析[参数#0[$methods]]在类Illuminate''Routing''Route中(视图:…
实际上,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);
}
}
如果未定义路由,将抛出NotFoundHttpException。异常在app/exceptions/handler.php.中的Larevel中进行管理
您必须检查异常是否为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);
}
来源。