springboot统一异常处理

其他的理论基础就不介绍了,我们直接上代码高效处理:

1.定义异常返回码

可以根据自己需求自定义code和message

复制代码
/**
 * @description: 统一返回码枚举
 * @Author yl
 * @Date 2024/3/13 16:15
 */
@Getter
@AllArgsConstructor
public enum ResultCodeEnum {

    ERROR_RESULT_CODE("9999","操作失败"),

    SUCCTESS_RESULT_CODE("0000","操作成功");

    private String code;
    private String message;
}

2.自定义异常类

复制代码
/**
 * @description: 自定义异常类
 * @Author yl
 * @Date 2024/3/13 9:43
 */
@Data
public class BusinessException extends RuntimeException{

    public BusinessException(String message){
        super(message);
    }

    public BusinessException(String msg, Object... objs) {
        super(MessageFormatter.arrayFormat(msg, objs).getMessage());
    }
}

3.捕获异常,对异常进行统一处理类:

我们系统抛出的所有异常,希望能有一个地方统一捕获异常后,以前后端约定的格式返回给前端:

复制代码
/**
 * @description: 统一异常处理类
 * @Author yl
 * @Date 2024/3/13 9:45
 */
@ControllerAdvice
public class BusinessExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(BusinessExceptionHandler.class);

    /**
     * 自定义业务异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public BaseResult<String> handleBusinessException(BusinessException e) {
        logger.error("自定义异常信息:{}",e.getMessage(), e);
        return BaseResult.errorResult(e.getMessage());
    }
    /**
     * 参数校验异常,将校验失败的所有异常组合成一条错误信息
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public BaseResult<String> handleValidException(MethodArgumentNotValidException e) {
        logger.error("参数绑定校验异常:{}", e.getMessage());
        List<FieldError> fieldError = e.getFieldErrors();
        StringBuilder sb = new StringBuilder();
        for (FieldError error : fieldError) {
            logger.info("error.getField:{}",error.getField());
            logger.info("defaultMessage:{}", error.getDefaultMessage());
            sb.append(error.getField()+error.getDefaultMessage()+",");
        }
        String result = sb.substring(0,sb.length()-1);
        logger.info("返回给前端的提示结果为:{}",result);
        return BaseResult.errorResult(result);
    }
    /**
     * 参数绑定异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public BaseResult<String> handleBindException(BindException e) {
        logger.error("参数绑定校验异常:{}", e.getMessage());

        return BaseResult.errorResult(e.getMessage());
    }
    /**
     * 参数异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public BaseResult<String> handleConstraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> cons = e.getConstraintViolations();
        StringBuilder sb = new StringBuilder();
        for (ConstraintViolation<?> con : cons) {
            Path path = con.getPropertyPath();
        }
        logger.error("handleConstraintViolationException参数绑定校验异常:{}", e.getLocalizedMessage());
        return BaseResult.errorResult(e.getLocalizedMessage());
    }
    /**
     * 参数类型不匹配常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public BaseResult<String> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        logger.error("参数类型不匹配异常:{}", e.getParameter());

        return BaseResult.errorResult(e.getMessage());
    }
    /**
     * 其他异常异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public BaseResult<String> handleRuntimeException(RuntimeException e) {
        logger.error("其他异常:{}", e);
        return BaseResult.errorResult(ResultCodeEnum.ERROR_RESULT_CODE);
    }
}

4.使用

直接抛出我们的自定义异常类:

相关推荐
程序员爱钓鱼27 分钟前
Go语言实战案例-简易计算器(加减乘除)
后端
学不会就看32 分钟前
Django--01基本请求与响应流程
后端·python·django
AI+程序员在路上35 分钟前
Qt6中模态与非模态对话框区别
开发语言·c++·qt
胚芽鞘6815 小时前
关于java项目中maven的理解
java·数据库·maven
nbsaas-boot5 小时前
Java 正则表达式白皮书:语法详解、工程实践与常用表达式库
开发语言·python·mysql
岁忧5 小时前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_7896 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
CJi0NG6 小时前
【自用】JavaSE--算法、正则表达式、异常
java
Nejosi_念旧6 小时前
解读 Go 中的 constraints包
后端·golang·go
风无雨6 小时前
GO 启动 简单服务
开发语言·后端·golang