【问题标题】:Laravel 5.2 - default error page for undefined routesLaravel 5.2 - 未定义路由的默认错误页面
【发布时间】:2016-08-02 00:08:10
【问题描述】:

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

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

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

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

我该怎么做?

提前致谢

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

哎呀,好像出了点问题。

错误异常在 C:\wamp\www\codes\laravel5\portpapa\vendor\laravel\framework\src\Illuminate\Container\Container.php 第 835 行:无法解析的依赖解析 [参数 #0 [ $methods ]] 在类 Illuminate\Routing\Route 中(查看:...

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.2


    【解决方案1】:

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

    【讨论】:

    • 我收到此错误:类 Illuminate\Routing\Route 中无法解析的依赖项解析 [Parameter #0 [ $methods ]]。我想我可能在某些不应该使用的地方使用了 Route。
    【解决方案2】:

    如果没有定义路由,会抛出 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.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-26
      • 2015-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 2018-06-27
      • 2016-06-24
      • 2019-01-15
      相关资源
      最近更新 更多