zoukankan      html  css  js  c++  java
  • laravel 框架配置404等异常页面

    在Laravel中所有的异常都由Handler类处理,该类包含两个方法:report和render,其中render方法将异常渲染到http响应中。laravel的Handler类文件位置:app/Exceptions/Handler,由于render方法时间异常渲染到http响应中,所以我们只需要修改下render方法即可

    网上很多的方法是将render方法修改成:

    public function render($request, Exception $exception)
    {
    if ($exception) {
    return response()->view('error.'.$exception->getStatusCode(), [],$exception->getStatusCode());
    }
    return parent::render($request, $exception);
    }

    这时候你的测试可能是没有问题的,但是如果你如果写了登录的方法的话,这时候如果你访问必须要登录的页面的时候,这时候会报错

    image.png

    这是由于如果你访问了必须要登录的页面的时候,这时候就会进入app/Exceptions/Handler.php的render方法,这时候$exception是有值的,然而$exception->getStatusCode()是不存在的,这时候就会报错了,那么如何解决呢?

    这时候我们找到parent::render的方法所在:

    image.png

    这时候我们发现原来laravel框架已经将我们的这种情况包含进去了,那么我们就可以即将上面的方法改为:

    public function render($request, Exception $exception)
    {
    if (!($exception instanceof AuthenticationException)) {
    return response()->view('error.'.$exception->getStatusCode(), [],$exception->getStatusCode());
    }
    return parent::render($request, $exception);
    }

    这时候就完美解决了这个问题

    然后在resources/view/error/下面新建错误页面,错误页面的命名为:{errorcode}..balde.php,其中的errorcode为错误码,例如404..balde.php

    配置完成后访问一个不存在的路由时即可跳转到你配置的404页面

  • 相关阅读:
    竞赛200
    竞赛202
    判断是node还是 浏览器端 typeof xxx==='string'
    闷油瓶
    关于算法题
    堆 heap, 准备博客参考
    私有npm 上发布 包
    竞赛199
    正则,转换数组
    设计模式之模板设计模式-以spring的各种template为例
  • 原文地址:https://www.cnblogs.com/huaweichenai/p/10232381.html
Copyright © 2011-2022 走看看