SpringBoot2.X(SpringMVC) 的异常处理机制

本文介绍了SpringBoot2.X的异常处理机制,包括系统异常和业务异常的统一处理。通过分析BasicErrorController源码及官方文档,展示了如何自定义异常代码,以及使用@RestControllerAdvice实现业务异常的全局捕获和处理。
摘要由CSDN通过智能技术生成

前言: SpringBoot2.X 异常分为 业务异常 和系统异常

  本博客以Springboot版本2.0.3为例,maven依赖如下,其他版本可能略有区别
 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

1. 系统异常统一处理

 默认系统异常处理(SpringBoot) 提供了两种机制,一种是针对于web浏览器访问的错误页面响应,另一种则是针对于 接口测试工具等 的参数响应处理):

浏览器访问返回的异常页面

postman访问放回的异常json格式
针对上面的2中放回格式,先看看Springboot的源码:BasicErrorController
在这里插入图片描述

  @RequestMapping(produces = "text/html")
  public ModelAndView errorHtml(HttpServletRequest request,
  		HttpServletResponse response) {
  	HttpStatus status = getStatus(request);
  	Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
  			request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
  	response.setStatus(status.value());
  	ModelAndView modelAndView = resolveErrorView(request, response, status, model);
  	return (modelAndView != null ? modelAndView : new ModelAndView("error", model));
  }

  @RequestMapping
  @ResponseBody
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
  	Map<String, Object> body = getErrorAttributes(request,
  			isIncludeStackTrace(request, MediaType.ALL));
  	HttpStatus status = getStatus(request);
  	re
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值