Spring-Boot全局异常处理

SpringBoot自带的异常处理

SpringBoot有一个默认的视图“/error”来处理所有的异常,并且该视图注册成全局的错误页面在服务中,在客户端中他返回带有状态和错误码的json类型的响应。

取代默认的视图来处理

To replace the default behavior completely, you can implement ErrorController and register a bean definition of that type or add a bean of type ErrorAttributes to use the existing mechanism but replace the contents.

自定义带注解的类处理

You can also define a class annotated with @ControllerAdvice to customize the JSON document to return for a particular controller and/or exception type

自定义错误处理类来返回json格式的响应

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@ControllerAdvice(basePackageClasses = AcmeController.class)
public class AcmeControllerAdvice extends ResponseEntityExceptionHandler {

@ExceptionHandler(YourException.class)
@ResponseBody
ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
HttpStatus status = getStatus(request);
return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status);
}

private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
}

}
  1. basePackageClasses: 标识限定控制器,可以去掉,以对所有控制器生效,会产生性能影响
  2. ExceptionHandler: 拦截自定义错误,可以去掉拦截所有错误类型
  3. handleControllerException: 在此方法中返回自定义的ResponseBody

参考