Spring Boot是怎么处理异常的

先一起来看看官方文档是怎么说明的
https://docs.spring.io/spring-boot/docs/2.3.0.RELEASE/reference/htmlsingle/#boot-features-error-handling


大致意思是Spring Boot提供了一个/error映射的handler来处理所有的错误,这个handler是BasicErrorController。如果是ajax这种形式的调用会返回一个JSON响应,如果是浏览器调用就返回一个错误的视图。
示例:

接下来一起看BasicErrorController


这个是响应json格式的错误信息的方法



那么这个Controller以及默认的错误视图是哪里注册到容器的呢,
来看ErrorMvcAutoConfiguration这个配置类
如图,注册了一个Bean



下面注册了默认的错误试图View

如何自定义错误处理

第一种,自定义错误试图
例如,将404错误映射到页面,就在resources/public/error目录下创建404.html



如果要加入更多的信息输出,还可以实现ErrorViewResolver



第二种:继承BasicErrorController,重写处理错误的方法
/*
@author : liyonglong
@description :自定义异常
@data: 2020/9/21 15:24
*/
public class CustomerErrorController extends BasicErrorController {
    public CustomerErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }

    @Override
    protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
        Map<String, Object> attributes = super.getErrorAttributes(request, includeStackTrace);
        attributes.remove("timestamp");
        attributes.remove("error");
        attributes.put("code", 500);
        return attributes;
    }
}

/*
@author : liyonglong
@description :异常相关配置类
@data: 2020/9/21 15:30
*/
@Configuration
public class ErrorConfiguration {
    @Bean
    public CustomerErrorController basicErrorController(ErrorAttributes errorAttributes,
                                                        ServerProperties serverProperties,
                                                        ObjectProvider<ErrorViewResolver> errorViewResolvers) {
        return new CustomerErrorController(errorAttributes, serverProperties.getError(), errorViewResolvers.orderedStream().collect(Collectors.toList()));
    }
}

也可以使用SpringMVC的特性ControllerAdvice

/*
@author : liyonglong
@description :controller的增强,AOP实现,可以用来处理异常
@data: 2020/9/21 15:40
*/
@ControllerAdvice(basePackages = "")
public class CustomerErrorAdvice {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    ResponseEntity handleControllerException(Throwable ex) {
        Map<String, Object> errorBody = new HashMap<>();
        errorBody.put("code", "500");
        errorBody.put("errorMessage", ex.getMessage());
        return new ResponseEntity(errorBody, HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

注:一旦在ControllerAdvice中捕获异常并正常返回后,那么异常就不会再被BasicErrorController捕获并处理,也就是ControllerAdvice先于BasicErrorController

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容