SpringBoot的两种统一错误处理方式

1.使用继承BasicErrorController 来实现
SpringBoot为我们提供了自动处理异常的BasicErrorController 其返回的JSON数据如下:

“timestamp”:…
“status”:…
“error”:…
“exception”:…
“path”:…
“message”:…

但一般 前端只需要我们传的message 信息,那么我们需要重新构造返回的JSON数据

(1)首先 创建错误枚举

/**
 * @BelongsProject: financial
 * @BelongsPackage: com.yhr.manager.error
 * @Author: yang
 * @CreateTime: 2019-03-26 13:14
 * @Description: 错误种类
 */
public enum ErrorEnum {

    ID_NOT_NULL("F001","编号不可为空",false),
    //,.,,,
    UNKNOWN("999","未知异常",false);


    private String code;
    private String message;
    private boolean canRestry;

    ErrorEnum(String code,String message,boolean canRestry){
        this.code=code;
        this.message=message;
        this.canRestry=canRestry;
    }

    public static ErrorEnum getByCode(String code){
        for (ErrorEnum errorEnum : ErrorEnum.values()) {
            if(errorEnum.code.equals(code)){
                return errorEnum;
            }
        }
        return UNKNOWN;
    }

    public String getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public boolean isCanRestry() {
        return canRestry;
    }}

(2)我们通过spring-boot-autoconfigure 依赖包下面 找到一个属性BasicErrorController
BasicErrorController ,创建MyErrorController 继承BasicErrorController 代码如下

public class MyErrorController extends BasicErrorController {
    public MyErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }


    /**
     * 自定义错误处理结果
     * 只要 message信息 并添加 code ,canRetry 信息
     * @param request
     * @param includeStackTrace
     * @return
     */
    @Override
    protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
        Map<String, Object>  attrs = super.getErrorAttributes(request, includeStackTrace);
        attrs.remove("timestamp");
        attrs.remove("status");
        attrs.remove("error");
        attrs.remove("exception");
        attrs.remove("path");
        String errorCode = (String) attrs.get("message");
        ErrorEnum errorEnum=ErrorEnum.getByCode(errorCode);
        attrs.put("message",errorEnum.getMessage());
        attrs.put("code",errorEnum.getCode());
        attrs.put("canRetry",errorEnum.isCanRestry());
        return  attrs;

    }
}

加入了我们自己需要的message code canRetry 。通过本身BasciController 里的message (这里的message是我们业务逻辑处理时

 Assert.notNull(product.getId(), ErrorEnum.ID_NOT_NULL.getCode());

而抛出的枚举ID_NOT_NULL ,我们将其捕获 并返回message code canRetry

(3)配置ErrorConfiguration
由于BasicErrorContorller 是被ErrorMvcAutoConfiguration 所注入的 于是我们找到ErrorMvcAutoConfiguration 注入BasicErrorController的方法

public ErrorMvcAutoConfiguration(ServerProperties serverProperties,
			ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) {
		this.serverProperties = serverProperties;
		this.errorViewResolvers = errorViewResolversProvider.getIfAvailable();
	}


	@Bean
	@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
	public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
		return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
				this.errorViewResolvers);
	}

因此我们创建自己的ErrorConfiguration ,复制上面的方法,并做修改
以下是我们自己的ErrorConfiguration代码

/**
 * @BelongsProject: financial
 * @BelongsPackage: com.yhr.manager.error
 * @Author: yang
 * @CreateTime: 2019-03-26 13:08
 * @Description: 错误处理相关配置
 */

/**
 * 从 ErrorMvcAutoConfiguration 里复制的方法 再进行改造
 */
@Configuration
public class ErrorConfiguration {

    @Bean
    @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
    public MyErrorController basicErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties, ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) {
        return new MyErrorController(errorAttributes, serverProperties.getError(),
                errorViewResolversProvider.getIfAvailable());
    }

}

好了至此 配置结束 我们查看结果 就得到我们想要返回的数据了
在这里插入图片描述

2.通过@ControllerAdvice 注解来处理统一错误
@ControllerAdivce 是比@Controller 的增强,对于这个注解 ,处理统一错误只是它的一种使用方式。

话不多说 代码如下:

/**
 * @BelongsProject: financial
 * @BelongsPackage: com.yhr.manager.error
 * @Author: yang
 * @CreateTime: 2019-03-26 13:27
 * @Description: 统一错误处理
 */
//
@ControllerAdvice("com.yhr.manager.controller")
public class ErrorControllerAdvice {


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity handleException(Exception e){
        Map<String, Object> attrs = new HashMap<>();
        String errorCode = (String) attrs.get("message");
        ErrorEnum errorEnum=ErrorEnum.getByCode(errorCode);
        attrs.put("message",errorEnum.getMessage());
        attrs.put("code",errorEnum.getCode());
        attrs.put("canRetry",errorEnum.isCanRestry());
        attrs.put("type","advice"); //这里加入这个只是测试一下 是否使用controller advice 来控制异常的
        return new ResponseEntity(attrs, HttpStatus.INTERNAL_SERVER_ERROR);
  }
}

@ControllerAdvice 里的参数可以指定增强控制器要扫描的包,如果制定了 只对这个包产生作用,不指定,是对全局抛出的错误都产生作用

这里我们加入一个type 属性 来看看两种处理统一错误共存情况下的处理顺序
我们访问:
在这里插入图片描述

由此可见 @ControllerAdvice是优先于MyErrorController处理的
如下图所示:
在这里插入图片描述
ControllerAdvice 是所有Controller外包裹的一层
如果我们在@ControllerAdvice里抛出一个异常,那么这个异常将会被下一级的MyErrorController处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【2021年,将Spring全家桶的课程进行Review,确保不再有课程的顺序错乱,从而导致学员看不懂。进入2022年,将Spring的课程进行整理,整理为案例精讲的系列课程,并开始加入高阶Spring Security等内容,一步步手把手教你从零开始学会应用Spring,课件将逐步进行上传,敬请期待!】 本课程是Spring全家桶系列课程的第三部分Spring Boot,Spring案例精讲课程以真实场景、项目实战为导向,循序渐进,深入浅出的讲解Java网络编程,助力您在技术工作中更进一步。 本课程聚焦Spring Boot核心知识点:整合Web(如:JSP、Thymeleaf、freemarker等的整合)的开发、全局异常处理、配置文件的配置访问、多环境的配置文件设置、日志Logback及slf4j的使用、国际化设置及使用, 并在最后以一个贯穿前后台的Spring Boot整合Mybatis的案例为终奖,使大家快速掌握Spring的核心知识,快速上手,为面试、工作都做好充足的准备。 由于本课程聚焦于案例,即直接上手操作,对于Spring的原理等不会做过多介绍,希望了解原理等内容的需要通过其他视频或者书籍去了解,建议按照该案例课程一步步做下来,之后再去进一步回顾原理,这样能够促进大家对原理有更好的理解。 【通过Spring全家桶,我们保证你能收获到以下几点】 1、掌握Spring全家桶主要部分的开发、实现2、可以使用Spring MVC、Spring Boot、Spring Cloud及Spring Data进行大部分的Spring开发3、初步了解使用微服务、了解使用Spring进行微服务的设计实现4、奠定扎实的Spring技术,具备了一定的独立开发的能力  【实力讲师】 毕业于清华大学软件学院软件工程专业,曾在Accenture、IBM等知名外企任管理及架构职位,近15年的JavaEE经验,近8年的Spring经验,一直致力于架构、设计、开发及管理工作,在电商、零售、制造业等有丰富的项目实施经验  【本课程适用人群】如果你是一定不要错过!  适合于有JavaEE基础的,如:JSP、JSTL、Java基础等的学习者没有基础的学习者跟着课程可以学习,但是需要补充相关基础知识后,才能很好的参与到相关的工作中。 【Spring全家桶课程共包含如下几门】 

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值