系统解耦问题-不同系统间dubbo调用的异常处理-ExceptionFilter

来源:互联网 发布:西门子系统数控编程 编辑:程序博客网 时间:2024/06/05 16:25

本文主要参考:浅谈dubbo的ExceptionFilter异常处理

问题描述,系统A和系统B使用了dubbo进行不同系统之间的调用,而B是从A解耦出的系统,所以B的自定义异常和A需要对接,我们一开始只是简单的迁移了异常类过来,实际使用的时候由于包名不同导致A抛出的异常和B签名不一致,这时dubbo会直接抛出异常。

解决思路:既然是dubbo传递的时候出现的问题,最佳方案还是在dubbo的异常处理机制上改动。如果捕获到异常来着A包目录,这转换成B包对应的异常类。

改动,参考 浅谈dubbo的ExceptionFilter异常处理

从dubbo的ExceptionFilter下手

public class ExceptionFilter implements Filter {    @Override    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {           try {            Result result = invoker.invoke(invocation);            if (result.hasException() && GenericService.class != invoker.getInterface()) {                try {                    Throwable exception = result.getException();                        if(exception instanceof b.exception.abException) {                        b.exception.abException ex = (b.exception.abException)exception;                        a.exception.XedkException nex = new a.exception.abException(ex.getCode(),ex.getMessage());                        nex.setStackTrace(ex.getStackTrace());                        return new RpcResult(nex);                      // 否则,包装成RuntimeException抛给客户端                    return new RpcResult(new RuntimeException(StringUtils.toString(exception)));                } catch (Throwable e) {                    return result;                }            }            return result;        } catch (RuntimeException e) {            logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost()                    + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName()                    + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e);            throw e;        }    }}

核心部分

            if(exception instanceof b.exception.abException) {                        b.exception.abException ex = (b.exception.abException)exception;                        a.exception.XedkException nex = new a.exception.abException(ex.getCode(),ex.getMessage());                        nex.setStackTrace(ex.getStackTrace());                        return new RpcResult(nex);              }
原创粉丝点击