本文主要是介绍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
- 文件内容
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抛出自定义异常的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!