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.使用

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

相关推荐
陈随易7 小时前
VSCode的Copilot扩展支持接入DeepSeek,Kimi了!
前端·后端·程序员
我不是外星人8 小时前
有了 Harness Engineering ,真的还需要研发工程师吗?
前端·后端·ai编程
candyTong8 小时前
RTK 技术原理:一次典型会话里,80% 上下文是怎么省下来的
javascript·后端·架构
Rust研习社11 小时前
组合真的优于继承吗?为什么 Rust 和 Go 都拥抱组合舍弃继承?
后端·rust·编程语言
IT_陈寒11 小时前
JavaScript的闭包把我坑惨了,说好的内存会自动回收呢?
前端·人工智能·后端
CaffeinePro12 小时前
Pydantic深度使用:数据校验、枚举、ORM映射
后端·fastapi
Chenyiax12 小时前
从 Chat 到 Responses:OpenAI API 抽象为什么变了?
后端
MariaH12 小时前
Koa和Express的区别
后端
MariaH12 小时前
Koa框架的使用
后端
luckdewei13 小时前
那个用 passlib 做认证的新同事,上线第一天就把用户密码写进了日志
后端