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

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

相关推荐
enjoy嚣士25 分钟前
springboot之Exel工具类
java·spring boot·后端·easyexcel·excel工具类
Thera77726 分钟前
C++ 高性能时间轮定时器:从单例设计到 Linux timerfd 深度优化
linux·开发语言·c++
罗超驿37 分钟前
独立实现双向链表_LinkedList
java·数据结构·链表·linkedlist
无限大61 小时前
职场逻辑03:3步搞定高效汇报,让领导看到你的价值
后端
炘爚1 小时前
C语言(文件操作)
c语言·开发语言
阿蒙Amon1 小时前
C#常用类库-详解SerialPort
开发语言·c#
盐水冰2 小时前
【烘焙坊项目】后端搭建(12) - 订单状态定时处理,来单提醒和顾客催单
java·后端·学习
凸头2 小时前
CompletableFuture 与 Future 对比与实战示例
java·开发语言
wuqingshun3141592 小时前
线程安全需要保证几个基本特征
java·开发语言·jvm
Moksha2622 小时前
5G、VoNR基本概念
开发语言·5g·php