spring-boot 集中处理异常
spring-boot配置方式集中处理异常,统一规范接口对外的异常输出。业务代码只需往外抛异常,不需过多关注异常的输出形式。
非系统抛出异常
对于400,404等非系统抛出的异常,使用以下方式:
1@Configuration
2public class ErrorHandler {
3
4 @Bean
5 public EmbeddedServletContainerCustomizer containerCustomizer() {
6 return new MyCustomizer();
7 }
8
9 private static class MyCustomizer implements
10 EmbeddedServletContainerCustomizer {
11 @Override
12 public void customize(ConfigurableEmbeddedServletContainer container) {
13 container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST,
14 "/400"));
15 container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404"));
16 }
17 }
18}
对于状态码为400,404的响应会转到相应的请求/400,/404中处理。
系统抛出异常
对于系统抛出的异常,除了跳到错误页面之外,我们常常需要记录错误日志等信息,因此不使用上述方法。而是在处理类和方法上加上注解@ControllerAdvice,@ExceptionHandler,如下:
1@Controller
2@ControllerAdvice
3public class ErrorController {
4
5 @RequestMapping(value = { "/404" })
6 @ResponseBody
7 public String notFound() {
8 return "404";
9 }
10
11 @ExceptionHandler(Exception.class)
12 @ResponseBody
13 public String handleException(Exception e) {
14 // 记录错误日志
15 return "Exception";
16 }
17}
在此类中一并处理非系统抛出异常,如上述的/404请求。
参考: Spring Boot Reference Guide, Spring Framework Reference Documentation
-END-
