dubbo rpc调用抛出的Exception处理
关于dubbo的Exception堆栈被吃处理,网上已经有比较多的解决方法,在我们的应用场景中,不希望RPC调用对方抛出业务exception,而是通过Resp中的errorCode,errorMsg来处理,例如有如下的定义:
@Override public ResultModel<String> createExpress(CreateExpressDTO dto) { // 参数验证 String group = ""; if (StringUtils.isNotBlank(dto.getPartyId())) { group = Group.PARTY_TYPE_PARTY; } else if (DictCons.BANK_ACCOUNT_TYPE__PUBLIC.equals(dto.getBankAccountType())) { group = Group.PARTY_TYPE_NOT_PARTY_PUB; } else { group = Group.PARTY_TYPE_NOT_PARTY_PRI; } ValidationResult validationResult = ValidationUtils.validateEntity(group, dto); if (!validationResult.isSuccess()) { return new ResultModel<>(ErrorCons.ERR_BS_BAD_PARAM, FastJsonUtil.serializeFromObject(validationResult.getErrorPair())); } 此处省去N行。。。。。
假设createExpress执行异常的时候,我们希望错误通过ResultModel<String>而不是RuntimeException回去,dubbo的exceptionfilter不符合我们的要求,如果要改动的话,需要到序列化层进行修改(原来在自己开发的RPC框架上就是这么处理的)。这种情况,只能借助AOP,如下:
package tf56.lf.common.advice; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import tf56.lf.base.ResultModel; import tf56.lf.base.metadata.err.ErrorCons; import tf56.lf.common.exception.LfException; import com.alibaba.fastjson.JSON; @Aspect public class ServiceAroundAdvice implements InitializingBean { private static final Logger logger = LoggerFactory.getLogger(ServiceAroundAdvice.class); @Around("execution(* tf56.lf.*.service..*(..))") public Object processDubboService(ProceedingJoinPoint jp) throws Throwable{ long begin = System.currentTimeMillis(); logger.info("开始执行" + jp.getSignature() + "参数:" + JSON.toJSONString(jp.getArgs())); Object result = null; try { result = jp.proceed(); } catch (Exception e) { logger.error("",e); Class<?> clz = ((MethodSignature)jp.getSignature()).getMethod().getReturnType(); if ("void".equals(clz.getName())) { return result; } ResultModel<?> resultModel = ((ResultModel<?>)clz.newInstance()); if (e instanceof LfException) { resultModel.setCode(((LfException) e).getCode()); resultModel.setMsg(((LfException) e).getErrorInfo()); } else { resultModel.setCode(ErrorCons.ERR_FAIL); } result = resultModel; } long end = System.currentTimeMillis(); logger.info("完成执行" + jp.getSignature() + ",共" + (end - begin) + "毫秒!"); return result; } @Override public void afterPropertiesSet() throws Exception { logger.info("加载" + this.getClass().getCanonicalName() + "成功!"); } }
增加配置如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean class="tf56.lf.common.advice.ServiceAroundAdvice"></bean> <aop:aspectj-autoproxy proxy-target-class="true" />
这样就可以保证所有的Exception都会被优雅的处理,同时泛型也都能恰当的被处理。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!