前言: 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浏览器访问的错误页面响应,另一种则是针对于 接口测试工具等 的参数响应处理):
针对上面的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