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

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

    @Override
    public 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);
            }
        }
    }

    @Override
    public 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)
    @ResponseBody
    public ResponseResult<Object> handleBaseException(BaseException e) {
        log.error("基础异常", e);
        return new ResponseResult<>(e.getCode(), e.getMessage());
    }

	// 其他异常捕获···
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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端口的功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值