- public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
- try {
- Result result = invoker.invoke(invocation);
- if (result.hasException() && GenericService.class != invoker.getInterface()) {
- try {
- Throwable exception = result.getException();
- // 如果是 checked 异常, 直接抛出
- if (! (exception instanceof RuntimeException) && (exception instanceof Exception)) {
- return result;
- }
- // 在方法签名上有声明, 直接抛出
- try {
- Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes());
- Class<?>[] exceptionClassses = method.getExceptionTypes();
- for (Class<?> exceptionClass : exceptionClassses) {
- if (exception.getClass().equals(exceptionClass)) {
- return result;
- }
- }
- } catch (NoSuchMethodException e) {
- return result;
- }
- // 未在方法签名上定义的异常, 在服务器端打印 ERROR 日志
- 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 result;
- }
- // 是 JDK 自带的异常, 直接抛出
- String className = exception.getClass().getName();
- if (className.startsWith("java.") || className.startsWith("javax.")) {
- return result;
- }
- // 是 Dubbo 本身的异常, 直接抛出
- if (exception instanceof RpcException) {
- return result;
- }
- // 否则, 包装成 RuntimeException 抛给客户端
- return new RpcResult(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);
- return result;
- }
- }
- return result;
- } catch (RuntimeException e) {
- 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);
- throw e;
- }
- }
1. 如果是 checked 异常, 直接抛出. 很明显, 我们的 HelloException 是 RuntimeException, 不符合
来源: http://www.bubuko.com/infodetail-2982963.html