SpringBoot Dubbo3 自定义异常处理

一、背景

        项目里用到了自定义异常,服务端抛出自定义异常,消费端取到的是RuntimeException,原因是dubbo默认的异常处理过滤器给进行了处理封装,过滤器为:org.apache.dubbo.rpc.filter.ExceptionFilter,处理的逻辑为(此处参照:https://blog.csdn.net/qq_36827957/article/details/89509749):

1.如果是checked异常,直接抛出.
2.在方法签名上有声明,直接抛出.
3.异常类和接口类在同一jar包里,直接抛出.
4.是JDK自带的异常,直接抛出.
5.是Dubbo本身的异常(RpcException),直接抛出.
6.否则,包装成RuntimeException抛给客户端.

如果能在项目中满足第2、3条,就不用下面的自定义异常过滤器

二、自定义异常处理过滤器

将原过滤器逻辑复制,添加自己的处理逻辑(中间部分添加判断是自定义异常直接返回):

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.*;
import org.apache.dubbo.rpc.filter.ExceptionFilter;
import org.apache.dubbo.rpc.service.GenericService;

import java.lang.reflect.Method;

import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION;

@Activate(group = CommonConstants.PROVIDER)
public class DubboExceptionFilter implements Filter, Filter.Listener {
    private ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExceptionFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        return invoker.invoke(invocation);
    }

    @Override
    public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
        if (appResponse.hasException() && GenericService.class != invoker.getInterface()) {
            try {
                Throwable exception = appResponse.getException();

                // directly throw if it's checked exception
                if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) {
                    return;
                }
                // directly throw if the exception appears in the signature
                try {
                    Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes());
                    Class<?>[] exceptionClasses = method.getExceptionTypes();
                    for (Class<?> exceptionClass : exceptionClasses) {
                        if (exception.getClass().equals(exceptionClass)) {
                            return;
                        }
                    }
                } catch (NoSuchMethodException e) {
                    return;
                }

                // for the exception not found in method's signature, print ERROR message in server's log.
                logger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "Got unchecked and undeclared exception which called by " + RpcContext.getServiceContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception);

                // directly throw if exception class and interface class are in the same jar file.
                String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface());
                String exceptionFile = ReflectUtils.getCodeBase(exception.getClass());
                if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)) {
                    return;
                }
                // directly throw if it's JDK exception
                String className = exception.getClass().getName();
                if (className.startsWith("java.") || className.startsWith("javax.")) {
                    return;
                }
                // directly throw if it's dubbo exception
                if (exception instanceof RpcException) {
                    return;
                }

                // 自定义异常直接返回
                if (exception instanceof MyException) {
                    return;
                }

                // otherwise, wrap with RuntimeException and throw back to the client
                appResponse.setException(new RuntimeException(StringUtils.toString(exception)));
            } catch (Throwable e) {
                logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "Fail to ExceptionFilter when called by " + RpcContext.getServiceContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e);
            }
        }
    }

    @Override
    public void onError(Throwable e, Invoker<?> invoker, Invocation invocation) {
        logger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "Got unchecked and undeclared exception which called by " + RpcContext.getServiceContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e);
    }

    // For test purpose
    public void setLogger(ErrorTypeAwareLogger logger) {
        this.logger = logger;
    }
}

在resources目录下创建文件:META-INF/dubbo/org.apache.dubbo.rpc.Filter

如图:

中间的META-INF目录和dubbo目录也需要自己创建 

文件org.apache.dubbo.rpc.Filter内容为(注意:文件名就叫org.apache.dubbo.rpc.Filter,必须是这样):

dubboExceptionFilter=com.provider.service.filter.DubboExceptionFilter

dubboExceptionFilter:随便取,不能和原有的重复,原有的不知道有些啥,取得长一点应该就不会重复😁

com.provider.service.filter.DubboExceptionFilter:我们刚刚创建的自定义异常过滤器全类名

要把原有的异常过滤器去掉,不然会有两个异常过滤器执行:

 -exception:减去原来叫 exception 的过滤器(即默认异常过滤器)

其他的不要看,只看红框部分

三、自定义异常报错(HessianProtocolException: ‘xxxException‘ could not be instantiated)

在消费者里面抛异常:HessianProtocolException: ‘xxxException‘ could not be instantiated

参考:https://blog.csdn.net/zipo/article/details/82959012

主要是自定义异常里面要有无参构造函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot集成Dubbo需要引入以下依赖: 1. dubbo-spring-boot-starter:版本为0.2.1.RELEASE,可以在仓库中查看具体的依赖信息\[1\]。 2. dubbo:具体版本可以在dubbo-spring-boot-starter的依赖中查看\[1\]。 3. log4j和slf4j的依赖。 4. spring-boot-starter-web:因为是以一个web服务进行启动,所以需要引入该依赖\[1\]。 在application.properties文件中,需要进行以下配置: 1. 配置dubbo口号和协议\[2\]。 2. 配置dubbo的接口所在包位置\[2\]。 在pom.xml文件中,需要引入以下依赖: 1. dubbo-interface模块:用于定义Dubbo的接口\[3\]。 2. spring-boot-starter和spring-boot-starter-web:用于启动Spring Boot应用\[3\]。 3. spring-boot-starter-dubbo:用于集成DubboSpring Boot\[3\]。 以上是Spring Boot集成Dubbo的基本配置和依赖引入。具体的配置和使用可以根据项目需求进行调整。 #### 引用[.reference_title] - *1* [SpringBoot集成Dubbo](https://blog.csdn.net/MX__LL/article/details/125537275)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [SpringBoot整合dubbo(一)](https://blog.csdn.net/chenguixu/article/details/127867833)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值