1、问题

使用@RestControllerAdvice添加了全局异常,但没有生效


/**
 * 全局异常处理
 * @author Eric
 * @date 2022-10-08 10:00:22
 */
@RestControllerAdvice
public class ExceptionControllerAdvice {

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

    /**
     * 用来拦截valid的校验
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object handleVaildException(MethodArgumentNotValidException e) {
        logger.info("数据校验出现问题:{},异常类型:{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        if (result.hasErrors()) {
            Map<String, String> errorMap = new HashMap<>();
            result.getFieldErrors().forEach((item) -> {
                //获取到的错误提示
                String message = item.getDefaultMessage();
                //获取到的错误属性名称
                String field = item.getField();
                errorMap.put(field, message);
            });
            return ResponseUtil.fail(DATA_ERROR.code(),errorMap);
        }
        return ResponseUtil.fail();
    }


    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Object notFount(RuntimeException e) {
        logger.info("运行时异常:", e);
        return ResponseUtil.fail(DATA_ERROR.code(),e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e) {
        logger.info(e.getMessage(), e);
        return ResponseUtil.fail(DATA_ERROR.code(),"服务器网络拥堵,请稍后再试");
    }

}

2、解决

方式1:@ExceptionHandler 所在类没有被Spring管理

因为 @SpringbootApplication默认扫描本包和子包,为了防止 全局异常类未被扫描到,建议在启动类上加上包扫描

在这里插入图片描述

方式2:AOP process() 没有异常抛出,自然不会被拦截掉。检查项目中的切面编程,查看是否在某个切面将异常try-catch,然后没有扔出来。

方式3:在@RestControllerAdvice @ConrollerAdivce 所在的类使用@Order(999999),注意这里不要引用错误的包了了,org.springframework.core.annotation.Order

在这里插入图片描述
参考1:参考1
参考2:参考2

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐