SpringBoot统一异常处理Dubbo异常,只捕获RuntimeException和Excpetion的处理方法笔记

在这里插入图片描述

场景

在Springboot中使用全局统一处理异常进行捕获,
平时能够正常使用,但是发现异常从dubbo调用返回以后,却进了RuntimeException的处理方法,如果没有就会直接进Exception的处理方法;
于时在报错中找到了一个ExceptionFilter
源码如下:

# 反正大概职能就是对特定的异常进行放行,然后其他全部包装成RuntimeException
# 为了便于阅读我删掉了日志类和构造
@Activate(group = Constants.PROVIDER)
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();

                    // 这里判断是不是RuntimeException或者是Exception是的话就放行了
                    if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) {
                        return result;
                    }
                    // 这里判断方法前面上是不是抛出了这个异常[经测,需要在接口上抛出,实现类抛出无效]
                    try {
                        Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes());
                        // 这里获取了方法上的所有异常,打断点就能看到,如果异常在接口上找到了就放行
                        Class<?>[] exceptionClassses = method.getExceptionTypes();
                        for (Class<?> exceptionClass : exceptionClassses) {
                            if (exception.getClass().equals(exceptionClass)) {
                                return result;
                            }
                        }
                    } catch (NoSuchMethodException e) {
                        return result;
                    }

                    // 这里如果都没处理就会在日志打印ERROR信息了,凎
                    logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost()
                            + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName()
                            + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception);

                    // 这里是在判断异常类和代理接口是不是在一个jar包,如果在也直接放行[不知道为啥,我异常拉过来还是不行,可能哪里有问题,不过我异常还是放回了common]
                    String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface());
                    String exceptionFile = ReflectUtils.getCodeBase(exception.getClass());
                    if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)) {
                        return result;
                    }
                    // 呐,这里就是放行了jdk的异常
                    String className = exception.getClass().getName();
                    if (className.startsWith("java.") || className.startsWith("javax.")) {
                        return result;
                    }
                    // 这里呢就放行了Rpc的异常
                    if (exception instanceof RpcException) {
                        return result;
                    }

                    // 如果全都不符合条件,就包装成一个RuntimeException抛出
                    return new RpcResult(new RuntimeException(StringUtils.toString(exception)));
                } catch (Throwable e) {
                    logger.warn("Fail to ExceptionFilter when called by " + RpcContext.getContext().getRemoteHost()
                            + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName()
                            + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), 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;
        }
    }

}

知道问题出在哪就试着去解决吧

解决

那我们先创建一个自定义异常过滤器CustomExceptionFilter然后去继承原来的ExceptionFilter过滤器,
重写invoker方法

/**
 * @author Guochar
 * 自定义异常过滤器,让dubbo放行自定义异常
 */
@Activate(group = Constants.PROVIDER)
public class CustomExceptionFilter extends ExceptionFilter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Result result = invoker.invoke(invocation); // 获取rpcResult
        // 如果没有异常发生 或者是通用服务就直接返回
        // 也可以沿用源码中 if (result.hasException() && GenericService.class != invoker.getInterface()){} return result;在else中返回的做法
        if (!result.hasException() || GenericService.class == invoker.getInterface())
            return result;
        Throwable exception = result.getException(); // 获取抛出的异常
        String classname = exception.getClass().getName();
        // 如果异常是我们这个路径里的异常,直接抛出,否则交给父类处理
        // 或者你们可以根据自己的需求进行放行,只需要完成判断后如果不符合就交给父类执行,否则就自己执行
        if (classname.startsWith("com.doria.common.exception"))
            return result;
        return super.invoke(invoker, invocation);
    }
}

自定义完了,我们现在就想办法让过滤器生效吧
我们在dubbo服务的resource下创建文件夹META-INF,再创建目录dubbo
然后创建文件com.alibaba.dubbo.rpc.Filter
加入一行数据
customExceptionFilter=com.doria.provider.filter.CustomExceptionFilter
参数需要是我们刚才路径的全路径
然后我们到配置文件中添加配置

# 自定义异常处理
dubbo.provider.filter=customExceptionFilter,-exception

现在我们重启服务,当异常发生时就会执行我们自定义的过滤器了

测试代码

/**
 * @author GuoChar
 * 测试
 */

@Service
public class TestApiImpl implements ITestApi {
    @Override
    public String get() {
        throw new VerificationException(200,20010,"验证未通过","用户验证未通过");
    }
}

/**
 * @GuoChar
 * 测试用
 */
@RestController
public class DemoController {
    @Reference
    private ITestApi testApi;

    @GetMapping(value = "get")
    public Result<Object> get(){
        return new Result<Object>(true,200,testApi.get());
    }

}

在这里插入图片描述

在这里插入图片描述
成功返回自定义异常并捕获

进一步了解请移步
另一个博主的文章
另一个解决方案,好像有挺多人在讨论

补充

关于配置中的
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
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值