Spring Boot全局统一异常处理器

 更新时间:2021年05月13日 16:34:08   作者:森-Js  
软件开发springboot项目过程中,不仅有大量的冗余代码,而且还影响代码的可读性.这样就需要定义个全局统一异常处理器,以便业务层再也不必处理异常.文中有非常详细的代码示例,需要的朋友可以参考下

一、封装统一返回结果类

import com.jiusen.exercise.enums.ErrorEnum;
import com.jiusen.exercise.exception.BusinessException;
import lombok.Getter;
import lombok.Setter;
 
/**
 * @author: Lawson
 * @date: 2021/5/11
 * @description: TODO 统一的返回结果
 */
@Getter
@Setter
public class AjaxResult {
 
    //是否成功
    private Boolean success;
    //状态码
    private Integer code;
    //提示信息
    private String msg;
    //数据
    private Object data;
 
    public AjaxResult() {
    }
 
    //自定义返回结果的构造方法
    public AjaxResult(Boolean success, Integer code, String msg, Object data) {
        this.success = success;
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
 
    //自定义异常返回的结果
    public static AjaxResult defineError(BusinessException de) {
        AjaxResult result = new AjaxResult();
        result.setSuccess(false);
        result.setCode(de.getErrorCode());
        result.setMsg(de.getErrorMsg());
        result.setData(null);
        return result;
    }
 
    //其他异常处理方法返回的结果
    public static AjaxResult otherError(ErrorEnum errorEnum){
        AjaxResult result = new AjaxResult();
        result.setMsg(errorEnum.getErrorMsg());
        result.setCode(errorEnum.getErrorCode());
        result.setSuccess(false);
        result.setData(null);
        return result;
    }
}

二、自定义异常封装类

import lombok.Getter;
import lombok.Setter;
 
/**
 * @author: Lawson
 * @date: 2021/5/11
 * @description: TODO 类描述
 */
@Getter
@Setter
public class BusinessException extends RuntimeException{
 
    private static final long serialVersionUID = 1L;
 
    /**
     * 错误状态码
     */
    protected Integer errorCode;
    /**
     * 错误提示
     */
    protected String errorMsg;
 
    public BusinessException() {
    }
 
    public BusinessException(String message, Integer errorCode, String errorMsg) {
        super(message);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }
}

三、错误枚举

**
 * @author: Lawson
 * @date: 2021/5/11
 * @description: TODO 类描述
 */
public enum  ErrorEnum {
    //数据操作错误定义
    SUCCESS(200, "成功"),
    NO_PERMISSION(403, "你无权访问"),
    NO_Auth(401, "未授权,请登录验证"),
    NO_FOUND(404, "未找到资源"),
    INTERNAL_SERVER_ERROR(500, "服务器异常, 请联系管理员!");
 
 
    /**
     * 错误码
     */
    private Integer errorCode;
    /**
     * 错误信息
     */
    private String errorMsg;
 
    ErrorEnum(Integer errorCode, String errorMsg) {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }
 
    public Integer getErrorCode() {
        return errorCode;
    }
 
    public String getErrorMsg() {
        return errorMsg;
    }
}

四、全局异常处理类

import com.jiusen.exercise.enums.ErrorEnum;
import com.jiusen.exercise.exception.BusinessException;
import com.jiusen.exercise.rest.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
 
 
/**
 * @author: Lawson
 * @date: 2021/5/11
 * @description: TODO 类描述
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
 
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
 
    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public AjaxResult bizExceptionHandler(BusinessException e) {
        log.error(e.getErrorMsg(), e);
        return AjaxResult.defineError(e);
    }
 
    /**
     * 处理其它异常
     */
    @ExceptionHandler(value = Exception.class)
    public AjaxResult exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return AjaxResult.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);
    }
}

五、测试

import com.jiusen.exercise.enums.ErrorEnum;
import com.jiusen.exercise.exception.BusinessException;
import com.jiusen.exercise.rest.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
 
 
/**
 * @author: Lawson
 * @date: 2021/5/11
 * @description: TODO 类描述
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
 
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
 
    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public AjaxResult bizExceptionHandler(BusinessException e) {
        log.error(e.getErrorMsg(), e);
        return AjaxResult.defineError(e);
    }
 
    /**
     * 处理其它异常
     */
    @ExceptionHandler(value = Exception.class)
    public AjaxResult exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return AjaxResult.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);
    }
}

到此这篇关于Spring Boot全局统一异常处理器的文章就介绍到这了,更多相关Spring Boot异常处理器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java实体对象与Map之间的转换工具类代码实例

    java实体对象与Map之间的转换工具类代码实例

    这篇文章主要介绍了java实体对象与Map之间的转换工具类代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • Struts2源码分析之ParametersInterceptor拦截器

    Struts2源码分析之ParametersInterceptor拦截器

    这篇文章主要介绍了Struts2源码分析之ParametersInterceptor拦截器,ParametersInterceptor拦截器其主要功能是把ActionContext中的请求参数设置到ValueStack中,,需要的朋友可以参考下
    2019-06-06
  • springboot中使用ConstraintValidatorContext验证两个字段内容相同

    springboot中使用ConstraintValidatorContext验证两个字段内容相同

    开发修改密码功能时,通过ConstraintValidator校验新密码和确认新密码的一致性,首先定义Matches注解和DTO对象,然后创建MatchesValidator类实现验证逻辑,对springboot验证字段内容相同问题感兴趣的朋友一起看看吧
    2024-10-10
  • Java两种方式实现动态代理

    Java两种方式实现动态代理

    Java 在 java.lang.reflect 包中有自己的代理支持,该类(Proxy.java)用于动态生成代理类,只需传入目标接口、目标接口的类加载器以及 InvocationHandler 便可为目标接口生成代理类及代理对象。我们称这个Java技术为:动态代理
    2020-10-10
  • springboot+thymeleaf打包成jar后找不到静态资源的坑及解决

    springboot+thymeleaf打包成jar后找不到静态资源的坑及解决

    这篇文章主要介绍了springboot+thymeleaf打包成jar后找不到静态资源的坑及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • java中TESTful架构原理分析

    java中TESTful架构原理分析

    这篇文章主要介绍了对java架构中TESTful架构原理进行了详细的原理分析,有需要的朋友可以借鉴参考下,希望可以有所帮助,祝大家多多进步,早日升职加薪
    2021-09-09
  • Maven工程路径映射的实现示例

    Maven工程路径映射的实现示例

    本文主要介绍了Maven工程路径映射的实现示例,文中通过图文介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-04-04
  • Spring Cache扩展功能实现过程解析

    Spring Cache扩展功能实现过程解析

    这篇文章主要介绍了Spring Cache扩展功能实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02
  • 零基础写Java知乎爬虫之准备工作

    零基础写Java知乎爬虫之准备工作

    上个系列我们从易到难介绍了如何使用python编写爬虫,小伙伴们反响挺大,这个系列我们来研究下使用Java编写知乎爬虫,小伙伴们可以对比这看下。
    2014-11-11
  • Spring Batch远程分区的本地Jar包模式的代码详解

    Spring Batch远程分区的本地Jar包模式的代码详解

    这篇文章主要介绍了Spring Batch远程分区的本地Jar包模式,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-09-09

最新评论