SpringBoot统一异常处理Dubbo异常
先上代码
场景
在Springboot中使用全局统一处理异常进行捕获,
平时能够正常使用,但是发现异常从dubbo调用返回以后,却进了RuntimeException的处理方法,如果没有就会直接进Exception的处理方法;
于时在报错中找到了一个ExceptionFilter
源码如下:
1 # 反正大概职能就是对特定的异常进行放行,然后其他全部包装成RuntimeException 2 # 为了便于阅读我删掉了日志类和构造 3 @Activate(group = Constants.PROVIDER) 4 public class ExceptionFilter implements Filter { 5 6 @Override 7 public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { 8 try { 9 Result result = invoker.invoke(invocation); 10 if (result.hasException() && GenericService.class != invoker.getInterface()) { 11 try { 12 Throwable exception = result.getException(); 13 14 // 这里判断是不是RuntimeException或者是Exception是的话就放行了 15 if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) { 16 return result; 17 } 18 // 这里判断方法前面上是不是抛出了这个异常[经测,需要在接口上抛出,实现类抛出无效] 19 try { 20 Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); 21 // 这里获取了方法上的所有异常,打断点就能看到,如果异常在接口上找到了就放行 22 Class<?>[] exceptionClassses = method.getExceptionTypes(); 23 for (Class<?> exceptionClass : exceptionClassses) { 24 if (exception.getClass().equals(exceptionClass)) { 25 return result; 26 } 27 } 28 } catch (NoSuchMethodException e) { 29 return result; 30 } 31 32 // 这里如果都没处理就会在日志打印ERROR信息了,凎 33 logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() 34 + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() 35 + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception); 36 37 // 这里是在判断异常类和代理接口是不是在一个jar包,如果在也直接放行[不知道为啥,我异常拉过来还是不行,可能哪里有问题,不过我异常还是放回了common] 38 String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface()); 39 String exceptionFile = ReflectUtils.getCodeBase(exception.getClass()); 40 if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)) { 41 return result; 42 } 43 // 呐,这里就是放行了jdk的异常 44 String className = exception.getClass().getName(); 45 if (className.startsWith("java.") || className.startsWith("javax.")) { 46 return result; 47 } 48 // 这里呢就放行了Rpc的异常 49 if (exception instanceof RpcException) { 50 return result; 51 } 52 53 // 如果全都不符合条件,就包装成一个RuntimeException抛出 54 return new RpcResult(new RuntimeException(StringUtils.toString(exception))); 55 } catch (Throwable e) { 56 logger.warn("Fail to ExceptionFilter when called by " + RpcContext.getContext().getRemoteHost() 57 + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() 58 + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); 59 return result; 60 } 61 } 62 return result; 63 } catch (RuntimeException e) { 64 logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() 65 + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() 66 + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); 67 throw e; 68 } 69 } 70 71 }
知道问题出在哪就试着去解决吧
解决
那我们先创建一个自定义异常过滤器CustomExceptionFilter
然后去继承原来的ExceptionFilter
过滤器,
重写invoker方法
1 /** 2 * @author Guochar 3 * 自定义异常过滤器,让dubbo放行自定义异常 4 */ 5 @Activate(group = Constants.PROVIDER) 6 public class CustomExceptionFilter extends ExceptionFilter { 7 8 @Override 9 public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { 10 Result result = invoker.invoke(invocation); // 获取rpcResult 11 // 如果没有异常发生 或者是通用服务就直接返回 12 // 也可以沿用源码中 if (result.hasException() && GenericService.class != invoker.getInterface()){} return result;在else中返回的做法 13 if (!result.hasException() || GenericService.class == invoker.getInterface()) 14 return result; 15 Throwable exception = result.getException(); // 获取抛出的异常 16 String classname = exception.getClass().getName(); 17 // 如果异常是我们这个路径里的异常,直接抛出,否则交给父类处理 18 // 或者你们可以根据自己的需求进行放行,只需要完成判断后如果不符合就交给父类执行,否则就自己执行 19 if (classname.startsWith("com.doria.common.exception")) 20 return result; 21 return super.invoke(invoker, invocation); 22 } 23 }
自定义完了,我们现在就想办法让过滤器生效吧
我们在dubbo服务的resource下创建文件夹META-INF,再创建目录dubbo
然后创建文件com.alibaba.dubbo.rpc.Filter
加入一行数据
customExceptionFilter=com.doria.provider.filter.CustomExceptionFilter
参数需要是我们刚才路径的全路径
然后我们到配置文件中添加配置
1 # 自定义异常处理 2 dubbo.provider.filter=customExceptionFilter,-exception
现在我们重启服务,当异常发生时就会执行我们自定义的过滤器了
测试代码
1 /** 2 * @author GuoChar 3 * 测试 4 */ 5 6 @Service 7 public class TestApiImpl implements ITestApi { 8 @Override 9 public String get() { 10 throw new VerificationException(200,20010,"验证未通过","用户验证未通过"); 11 } 12 } 13 14 /** 15 * @GuoChar 16 * 测试用 17 */ 18 @RestController 19 public class DemoController { 20 @Reference 21 private ITestApi testApi; 22 23 @GetMapping(value = "get") 24 public Result<Object> get(){ 25 return new Result<Object>(true,200,testApi.get()); 26 } 27 28 }
成功返回自定义异常并捕获
补充
关于配置中的
dubbo.provider.filter=customExceptionFilter,-exception
将自己定义的过滤器注册进去,多个以逗号分隔,后面的-则表示使这个名称的过滤器失效,
场景一 [false]
dubbo.provider.filter=customExceptionFilter同时抛出的是我们过滤器可以处理的异常
异常会进入我们定义的过滤器并且被我们放行,但是由于没有删除原本的过滤器,异常还会进入原本的过滤器届时又会被封装为RuntimeException返回;
场景二[true]
dubbo.provider.filter=customExceptionFilter,-exception,同时抛出的是我们过滤器可以处理的异常
异常进入我们的定义的过滤被直接抛出,由于原始过滤被屏蔽,所以可以正确返回我们捕获的自定义异常
场景三[true]
dubbo.provider.filter=customExceptionFilter,-exception,抛出的是我们无法处理的异常
异常进入我们的过滤器以后并没有被我们执行,所以交由supper调用父类执行原来的方法封装为RuntimeException返回,我们大可不必整个复制过来,只需要在执行我们的判断以后如果没被我们处理就调用原始方法;
场景四[false]
dubbo.provider.filter=customExceptionFilter,-exceptionA,抛出的是我们可处理的异常
由于这里根本不会进入我们设置的异常过滤器,所以抛出那种异常都一样,会交由原始过滤器处理
【疑问,为什么删除原始过滤器失败,会导致进不去我们设定的过滤器呢,还是根本就不是这个机制】所以不确定,日后再补充
拓展问题
问题1:升级到2.7.2后,怎么没有RpcResult类了?用什么代替呢?
Filter链路上传递的对象变成了AsyncRpcResult, 所以修改返回值现在只需要result.setValue(response) 应该就好了
转自:https://blog.csdn.net/m0_49194578/article/details/124132772
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示