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异常失效内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论