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

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

相关推荐
L Jiawen3 分钟前
【Go · Gin】基础知识
开发语言·golang·gin
学博成11 分钟前
在 Spring Boot 中使用 Kafka 并保证顺序性(Topic 分区为 100)的完整案例
spring boot·kafka
無欲無为1 小时前
Spring Boot 整合 RabbitMQ 详细指南:从入门到实战
spring boot·rabbitmq·java-rabbitmq
掘根1 小时前
【消息队列项目】客户端四大模块实现
开发语言·后端·ruby
疯狂的挖掘机7 小时前
记一次基于QT的图片操作处理优化思路(包括在图上放大缩小,截图,画线,取值等)
开发语言·数据库·qt
cnxy1887 小时前
围棋对弈Python程序开发完整指南:步骤4 - 提子逻辑和劫争规则实现
开发语言·python·机器学习
NAGNIP7 小时前
多个 GitHub 账户SSH 密钥配置全攻略
后端
NAGNIP7 小时前
Windows命令行代码自动补全详细步骤
后端
意趣新8 小时前
C 语言源文件从编写完成到最终生成可执行文件的完整、详细过程
c语言·开发语言
.鸣8 小时前
set和map
java·学习