栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot-16错误处理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot-16错误处理

1、默认处理

当访问页面时是返回404,500等错误信息

  • 默认情况下,Spring Boot提供/error处理所有错误的映射。
  • 如果是浏览器请求URL错误,返回错误页面;如果是postman等非浏览器客户端请求URL错误,返回 json 数据。

浏览器客户端
机器客户端

2、自定义
  • 要对其进行自定义,添加View解析为error;
  • error/404.html error/5xx.html;有精确的错误状态码页面就匹配精确,没有就找 4xx.html;如果都没有就触发白页。
  • 注意:
    html文件要引入模板引擎;
    拦截器放开静态资源;

如果在 templates/error 目录下有自定义的 4xx 或 5xx 页面,则使用此页面;

如果templates/error 目录下没有自定义的错误页面:在 static/error 目录下寻找 4xx 或 5xx 页面,如果找到则使用;

如果 templates/error目录和 static/error目录都没有自定义的 4xx 或 5xx 页面 ,则使用 SpringBoot默认的错误页面

3、源码
@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {
    // 浏览器:
    @RequestMapping( produces = {"text/html"} )
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = this.getStatus(request);
        // 在这里填充返回的属性值
        Map model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());
        // 在这里填充返回的页面
        ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
        return modelAndView != null ? modelAndView : new ModelAndView("error", model);
    }
 
    // 其他客户端: 
    @RequestMapping
    public ResponseEntity> error(HttpServletRequest request) {
        // 在这里填充返回的属性值
        Map body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = this.getStatus(request);
        return new ResponseEntity(body, status);
    }
 
    
}
 
 
public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered {
     private ModelAndView resolve(String viewName, Map model) {
        // 默认去找到error/下的错误页面
        String errorViewName = "error/" + viewName;
        // 模板引擎寻找错误页面代码
        TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);
        return provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model);
    }
}​
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/337917.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号