当前位置: 代码网 > it编程>编程语言>Java > SpringBoot项目中@RestControllerAdvice全局异常失效问题的解决

SpringBoot项目中@RestControllerAdvice全局异常失效问题的解决

2024年11月02日 Java 我要评论
1、问题使用@restcontrolleradvice添加了全局异常,但没有生效/** * 全局异常处理 * @author eric * @date 2022-10-08 10:00:22 */@r

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

到此这篇关于springboot项目中@restcontrolleradvice全局异常失效问题的解决的文章就介绍到这了,更多相关springboot @restcontroller异常失效内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com