dubbo抛出自定义异常

2023-11-22 20:10
文章标签 异常 定义 dubbo 出自

本文主要是介绍dubbo抛出自定义异常,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

2021-08-25 更新:
更简单的方案是在接口上声明抛出自定义异常。因为自定义的异常为RuntimeException,所以调用方无需try catch。无需重写和配置ExceptionFilter,dubbo也会对这个异常继续向上抛出。


重写ExceptionFilter

package com.*.microservice.common.filter;import com.jumi.microservice.common.exception.BaseException;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.Logger;
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.service.GenericService;import java.lang.reflect.Method;/*** @author Dirk* @date 2020-11-07 11:39*/
@Activate(group = CommonConstants.PROVIDER)
public class ExceptionFilter implements Filter, Filter.Listener {private final Logger logger = LoggerFactory.getLogger(ExceptionFilter.class);@Overridepublic Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {return invoker.invoke(invocation);}@Overridepublic void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {// 如果有异常并且未实现GenericService接口,进入后续判断逻辑if (appResponse.hasException() && GenericService.class != invoker.getInterface()) {try {Throwable exception = appResponse.getException();// 检查异常,直接抛出if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) {return;}// 方法签名上有说明抛出非检查异常,直接抛出try {Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes());Class<?>[] exceptionClassses = method.getExceptionTypes();for (Class<?> exceptionClass : exceptionClassses) {if (exception.getClass().equals(exceptionClass)) {return;}}} catch (NoSuchMethodException e) {return;}// 自定义异常直接抛出if (exception instanceof BaseException) {return;}// 对于方法签名中未找到的异常,请在服务器日志中打印错误消息。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;}// JDK异常,直接抛出String className = exception.getClass().getName();if (className.startsWith("java.") || className.startsWith("javax.")) {return;}// dubbo异常,直接抛出if (exception instanceof RpcException) {return;}// 否则,包装成RuntimeException抛给客户端appResponse.setException(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);}}}@Overridepublic void onError(Throwable e, Invoker<?> invoker, Invocation invocation) {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);}
}

配置ExceptionFilter

  • 创建两级文件夹META-INF/dubbo/,添加文件org.apache.dubbo.rpc.Filter
    配置dubbo
  • 文件内容
exception=com.jumi.microservice.common.filter.ExceptionFilter

自定义异常类

public class BaseException extends RuntimeException {private static final long serialVersionUID = -2789990150758271257L;private int code;private String message;public BaseException() {}public BaseException(int code, String message) {this.code = code;this.message = message;}// BaseExceptionEnum是自定义异常枚举接口public BaseException(ExceptionEnum exceptionEnum) {this.code = exceptionEnum.getCode();this.message = exceptionEnum.getMessage();}// getter and setter
}

全局异常捕捉

/*** 全局异常处理类*/
@Component
@ControllerAdvice
@ConditionalOnWebApplication
public class GlobalExceptionHandler {private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);/*** 基础异常** @param e 异常* @return 异常结果*/@ExceptionHandler(value = BaseException.class)@ResponseBodypublic ResponseResult<Object> handleBaseException(BaseException e) {log.error("基础异常", e);return new ResponseResult<>(e.getCode(), e.getMessage());}// 其他异常捕获···
}

这篇关于dubbo抛出自定义异常的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/412625

相关文章

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

Spring Boot 中的默认异常处理机制及执行流程

《SpringBoot中的默认异常处理机制及执行流程》SpringBoot内置BasicErrorController,自动处理异常并生成HTML/JSON响应,支持自定义错误路径、配置及扩展,如... 目录Spring Boot 异常处理机制详解默认错误页面功能自动异常转换机制错误属性配置选项默认错误处理

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束

SpringBoot整合Dubbo+ZK注册失败的坑及解决

《SpringBoot整合Dubbo+ZK注册失败的坑及解决》使用Dubbo框架时,需在公共pom添加依赖,启动类加@EnableDubbo,实现类用@DubboService替代@Service,配... 目录1.先看下公共的pom(maven创建的pom工程)2.启动类上加@EnableDubbo3.实

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Java进程异常故障定位及排查过程

《Java进程异常故障定位及排查过程》:本文主要介绍Java进程异常故障定位及排查过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、故障发现与初步判断1. 监控系统告警2. 日志初步分析二、核心排查工具与步骤1. 进程状态检查2. CPU 飙升问题3. 内存

使用Python进行GRPC和Dubbo协议的高级测试

《使用Python进行GRPC和Dubbo协议的高级测试》GRPC(GoogleRemoteProcedureCall)是一种高性能、开源的远程过程调用(RPC)框架,Dubbo是一种高性能的分布式服... 目录01 GRPC测试安装gRPC编写.proto文件实现服务02 Dubbo测试1. 安装Dubb

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

CSS Anchor Positioning重新定义锚点定位的时代来临(最新推荐)

《CSSAnchorPositioning重新定义锚点定位的时代来临(最新推荐)》CSSAnchorPositioning是一项仍在草案中的新特性,由Chrome125开始提供原生支持需... 目录 css Anchor Positioning:重新定义「锚定定位」的时代来了! 什么是 Anchor Pos