laravel 自定义错误页面

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/YuYan_wang/article/details/53099702

在以往版本的 Laravel 中,假如你想自定义错误页面——比如当用户访问不存在的页面时显示一张熊猫的图片.

在 Laravel 5 中,这个问题得到了改进。

源代码解析

在新版本的 Laravel 中,所以处理自定义错误和异常的代码都移到了 app/Exceptions/Handler.php 里。

但阅读代码时你可能发现了,默认是这样处理的:

    /**
          * Render an exception into an HTTP response.
            *
           * @param  \Illuminate\Http\Request  $request
           * @param  \Exception  $e
          * @return \Illuminate\Http\Response

     */
    public function render($request, Exception $e)
    {
        if ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        }

        return parent::render($request, $e);
    }

对所有的 HTTP 异常(比如 404 或者 503 这样的异常),获取错误码。并返回给父元素,所以我们继续追溯到它的父类, Illuminate\Foundation\Exceptions\Handler , 在这个类里面,我们找到了 renderHttpException() 方法的代码:

    /**
     * Render the given HttpException.
     *
     * @param  \Symfony\Component\HttpKernel\Exception\HttpException  $e
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function renderHttpException(HttpException $e)
    {
        $status = $e->getStatusCode();


        if (view()->exists("errors.{$status}")) {
            return response()->view("errors.{$status}", ['exception' => $e], $status);
        } else {
            return $this->convertExceptionToResponse($e);
        }
    }

如何实现自定义页面

根据上述分析我们只需在  resources\views  新建一个errors目录 ,在里面创建错误文件,例如:404.blade.php    503.blade.php  等等,实现自定义错误页面就这么简单

猜你喜欢

转载自blog.csdn.net/YuYan_wang/article/details/53099702