Dubbo抛出自定义异常

        最近开始学习Dubbo框架,在工作中会把之前的业务迁移过来。

        在原来的Spring MVC框架实现中,有使用到自定义异常的场景(自定义异常继承RuntimeException)。而对于异常(包括自定义异常),在业务代码中都不做任何try-catch操作,而是由公用的Controller来处理异常。

        在使用dubbo的过程中,在dubbo的service端定义有自定义异常进行throw的时候,却发现在customer的Controller中无法instanceof,自己自定义的异常类被转成了Runtime异常,有点不理解。在翻看dubbo源码的时候,发现确实如此:

    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();

                    // 如果是checked异常,直接抛出
                    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包里,直接抛出
                    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;
                    }
                    // 是Dubbo本身的异常,直接抛出
                    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;
        }
    }
        所以在dubbo的service端想抛出自定义异常,只能通过在service端的接口方法上声明所要抛出的异常,或者将异常类与接口同包,再或者是接口的实现类再实现dubbo的GenericService接口。

        对于第一种方案没有使用,因为它对代码的入侵比较严重。

        第二种方案可以实现,可对于目前的业务框架,让接口类和异常类同包则变得不太可能。

        所以最后选择了让接口实现类再实现GenericService接口,而对于其需要实现的$invoke方法则没有做任何的方法体处理,直接废弃。


        对于dubbo的service端自定义异常类的处理,有些不理解的就是,为什么dubbo需要对自定义异常类做一次Runtime异常的转化,而不是直接抛出原异常类型。或者有没有对dubbo更了解的朋友,有对自定义异常更好的处理方法。


Dubbo中,可以通过自定义异常来实现屏蔽IP口的功能。 首先,可以定义一个自定义异常类,例如BlockedIPException,用于表示被屏蔽的IP地址和口号。 ```java public class BlockedIPException extends RuntimeException { private String ip; private int port; public BlockedIPException(String ip, int port) { super("IP " + ip + ":" + port + " has been blocked!"); this.ip = ip; this.port = port; } public String getIp() { return ip; } public int getPort() { return port; } } ``` 然后,在服务提供者中,可以通过实现Dubbo的ExceptionFilter接口,在invoke()方法中判断请求的IP地址和口号是否被屏蔽,如果是,则抛出BlockedIPException异常。 ```java public class IPBlockExceptionFilter implements ExceptionFilter { private Set<String> blockedIps = new HashSet<>(); public IPBlockExceptionFilter() { // 初始化屏蔽的IP地址和口号 blockedIps.add("127.0.0.1:8080"); } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { // 获取请求的IP地址和口号 String remoteAddress = RpcContext.getContext().getRemoteAddressString(); if (blockedIps.contains(remoteAddress)) { throw new BlockedIPException(remoteAddress.split(":")[0], Integer.parseInt(remoteAddress.split(":")[1])); } return invoker.invoke(invocation); } } ``` 最后,在服务提供者的配置文件中,将IPBlockExceptionFilter配置为异常过滤器即可。 ```xml <dubbo:service interface="com.example.demo.DemoService" ref="demoService"> <dubbo:parameter key="exception-filter" value="com.example.demo.filter.IPBlockExceptionFilter"/> </dubbo:service> ``` 这样,当客户请求的IP地址和口号被屏蔽时,Dubbo框架抛出BlockedIPException异常,可以通过该异常来实现屏蔽IP口的功能。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值