org.apache.dubbo.rpc.RpcException Java Examples

The following examples show how to use org.apache.dubbo.rpc.RpcException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ITTracingFilter_Consumer.java    From brave with Apache License 2.0 6 votes vote down vote up
/** Shows if you aren't using RpcTracing, the old "dubbo.error_code" works */
@Test public void setError_onUnimplemented_legacy() {
  ((TracingFilter) ExtensionLoader.getExtensionLoader(Filter.class)
      .getExtension("tracing")).isInit = false;

  ((TracingFilter) ExtensionLoader.getExtensionLoader(Filter.class)
      .getExtension("tracing"))
      .setTracing(tracing);

  assertThatThrownBy(() -> wrongClient.get().sayHello("jorge"))
      .isInstanceOf(RpcException.class);

  MutableSpan span =
      testSpanHandler.takeRemoteSpanWithErrorMessage(CLIENT, ".*Not found exported service.*");
  assertThat(span.tags())
      .containsEntry("dubbo.error_code", "1");
}
 
Example #2
Source File: UserLoadBalance.java    From dubbo-samples with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
    for (Invoker t : invokers) {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            String ip = addr.getHostAddress().toString();
            URL u = t.getUrl();
            if (u.getIp().equals(ip)) {
                return t;
            }
        } catch (Exception e) {
            // no op
        }
    }
    return super.doSelect(invokers, url, invocation);
}
 
Example #3
Source File: DubboSofaTracerFilter.java    From sofa-tracer with Apache License 2.0 6 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    // do not record
    if ("$echo".equals(invocation.getMethodName())) {
        return invoker.invoke(invocation);
    }

    RpcContext rpcContext = RpcContext.getContext();
    // get appName
    if (StringUtils.isBlank(this.appName)) {
        this.appName = SofaTracerConfiguration
            .getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY);
    }
    // get span kind by rpc request type
    String spanKind = spanKind(rpcContext);
    Result result;
    if (spanKind.equals(Tags.SPAN_KIND_SERVER)) {
        result = doServerFilter(invoker, invocation);
    } else {
        result = doClientFilter(rpcContext, invoker, invocation);
    }
    return result;
}
 
Example #4
Source File: Resilience4jCircuitBreakerFilter.java    From dubbo-samples with Apache License 2.0 6 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    System.out.println("**************** Enter CircuitBreaker ****************");
    long countLong = count.incrementAndGet();
    long start = 0;
    try {
        CircuitBreakerUtils.isCallPermitted(circuitBreaker);
        start = System.nanoTime();
        Result result = invoker.invoke(invocation);
        if (result.hasException()) {
            doThrowException(result.getException(), start);
            return result;
        }
        long durationInNanos = System.nanoTime() - start;
        circuitBreaker.onSuccess(durationInNanos);
        return result;
    } catch (CircuitBreakerOpenException cbo) {

        doCircuitBreakerOpenException(cbo, countLong, breakCount.incrementAndGet());
        throw cbo;
    } catch (Throwable throwable) {
        doThrowException(throwable, start);
        throw throwable;
    }
}
 
Example #5
Source File: DubboParserTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void errorCodes() {
  assertThat(DubboParser.errorCode(null))
      .isEqualTo(DubboParser.errorCode(new IOException("timeout")))
      .isNull();

  assertThat(DubboParser.errorCode(new RpcException(0)))
      .isEqualTo("UNKNOWN_EXCEPTION");
  assertThat(DubboParser.errorCode(new RpcException(1)))
      .isEqualTo("NETWORK_EXCEPTION");
  assertThat(DubboParser.errorCode(new RpcException(2)))
      .isEqualTo("TIMEOUT_EXCEPTION");
  assertThat(DubboParser.errorCode(new RpcException(3)))
      .isEqualTo("BIZ_EXCEPTION");
  assertThat(DubboParser.errorCode(new RpcException(4)))
      .isEqualTo("FORBIDDEN_EXCEPTION");
  assertThat(DubboParser.errorCode(new RpcException(5)))
      .isEqualTo("SERIALIZATION_EXCEPTION");
  assertThat(DubboParser.errorCode(new RpcException(6)))
      .isEqualTo("NO_INVOKER_AVAILABLE_AFTER_FILTER");
  assertThat(DubboParser.errorCode(new RpcException(7)))
      .isEqualTo("LIMIT_EXCEEDED_EXCEPTION");
  assertThat(DubboParser.errorCode(new RpcException(8)))
      .isNull(); // This test will drift with a new error code name if Dubbo adds one.
}
 
Example #6
Source File: LegacyBlockFilter.java    From dubbo-samples with Apache License 2.0 6 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    RpcContext context = RpcContext.getContext();
    String filters = (String) context.getAttachment("filters");
    if (StringUtils.isEmpty(filters)) {
        filters = "";
    }
    filters += " legacy-block-filter";
    context.setAttachment("filters", filters);

    Result result = invoker.invoke(invocation);

    logger.info("This is the default return value: " + result.getValue());

    if (result.hasException()) {
        System.out.println("LegacyBlockFilter: This will only happen when the real exception returns: " + result.getException());
        logger.warn("This will only happen when the real exception returns", result.getException());
    }

    logger.info("LegacyBlockFilter: This msg should not be blocked.");
    return result;
}
 
Example #7
Source File: BirdExceptionFilter.java    From bird-java with MIT License 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    try {
        return invoker.invoke(invocation);
    } 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;
    }
}
 
Example #8
Source File: DubboAppContextFilter.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
    if (application != null) {
        RpcContext.getContext().setAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, application);
    }
    return invoker.invoke(invocation);
}
 
Example #9
Source File: Resilience4jRateLimiterFilter.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    try {
        System.out.println("**************** Enter RateLimiter ****************");
        RateLimiter.waitForPermission(rateLimiter);
        return invoker.invoke(invocation);
    } catch (RequestNotPermitted rnp) {
        System.err.println("---------------- Rate Limiter! Try it later! ----------------");
        throw rnp;
    } catch (Throwable throwable) {
        System.err.println("........" + throwable.getMessage());
        throw throwable;
    }
}
 
Example #10
Source File: EDASIT.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testGreeting() throws Exception {
    // FIXME, no provider
    try {
        System.out.println(dubboConsumer.callDemoService());
    } catch (Exception e) {
        Assert.assertTrue(e instanceof RpcException);
        Assert.assertTrue(((RpcException) e).getMessage().contains("No provider available"));
    }
}
 
Example #11
Source File: AsyncPostprocessFilter.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    RpcContext context = RpcContext.getContext();
    String filters = (String) context.getAttachment("filters");
    if (StringUtils.isEmpty(filters)) {
        filters = "";
    }
    filters += " async-post-process-filter";
    context.setAttachment("filters", filters);

    return invoker.invoke(invocation);
}
 
Example #12
Source File: LegacyListenableFilter.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    RpcContext context = RpcContext.getContext();
    String filters = (String) context.getAttachment("filters");
    if (StringUtils.isEmpty(filters)) {
        filters = "";
    }
    filters += " legacy-block-filter";
    context.setAttachment("filters", filters);

    return invoker.invoke(invocation);
}
 
Example #13
Source File: ThrowableAsyncFilter.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    if (invocation != null) {
        throw new RuntimeException("exception before invoke()");
    }
    return invoker.invoke(invocation);
}
 
Example #14
Source File: DubboParser.java    From brave with Apache License 2.0 5 votes vote down vote up
/**
 * On occasion, (roughly once a year) Dubbo adds more error code numbers. When this occurs, do not
 * use the symbol name, in the switch statement, as it will affect the minimum version.
 */
@Nullable static String errorCode(Throwable error) {
  if (error instanceof RpcException) {
    return ERROR_CODE_NUMBER_TO_NAME.get(((RpcException) error).getCode());
  }
  return null;
}
 
Example #15
Source File: SentinelDubboConsumerFilter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    InvokeMode invokeMode = RpcUtils.getInvokeMode(invoker.getUrl(), invocation);
    if (InvokeMode.SYNC == invokeMode) {
        return syncInvoke(invoker, invocation);
    } else {
        return asyncInvoke(invoker, invocation);
    }

}
 
Example #16
Source File: DubboAppContextFilter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    String application = invoker.getUrl().getParameter(CommonConstants.APPLICATION_KEY);
    if (application != null) {
        RpcContext.getContext().setAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, application);
    }
    return invoker.invoke(invocation);
}
 
Example #17
Source File: ITTracingFilter_Consumer.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void onTransportException_setError() {
  server.stop();

  assertThatThrownBy(() -> client.get().sayHello("jorge"))
      .isInstanceOf(RpcException.class);

  testSpanHandler.takeRemoteSpanWithErrorMessage(CLIENT, ".*RemotingException.*");
}
 
Example #18
Source File: ITTracingFilter_Consumer.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void setError_onUnimplemented() {
  assertThatThrownBy(() -> wrongClient.get().sayHello("jorge"))
      .isInstanceOf(RpcException.class);

  MutableSpan span =
      testSpanHandler.takeRemoteSpanWithErrorMessage(CLIENT, ".*Not found exported service.*");
  assertThat(span.tags())
      .containsEntry("dubbo.error_code", "1");
}
 
Example #19
Source File: DubboSofaTracerFilter.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
@Override
public Result onResponse(Result result, Invoker<?> invoker, Invocation invocation) {
    String spanKey = getTracerSpanMapKey(invoker);
    try {
        // only the asynchronous callback to print
        boolean isAsync = RpcUtils.isAsync(invoker.getUrl(), invocation);
        if (!isAsync) {
            return result;
        }
        if (TracerSpanMap.containsKey(spanKey)) {
            SofaTracerSpan sofaTracerSpan = TracerSpanMap.get(spanKey);
            // to build tracer instance
            if (dubboConsumerSofaTracer == null) {
                this.dubboConsumerSofaTracer = DubboConsumerSofaTracer
                    .getDubboConsumerSofaTracerSingleton();
            }
            String resultCode = SofaTracerConstant.RESULT_CODE_SUCCESS;
            if (result.hasException()) {
                if (result.getException() instanceof RpcException) {
                    resultCode = Integer.toString(((RpcException) result.getException())
                        .getCode());
                    sofaTracerSpan.setTag(CommonSpanTags.RESULT_CODE, resultCode);
                } else {
                    resultCode = SofaTracerConstant.RESULT_CODE_ERROR;
                }
            }
            // add elapsed time
            appendElapsedTimeTags(invocation, sofaTracerSpan, result, true);
            dubboConsumerSofaTracer.clientReceiveTagFinish(sofaTracerSpan, resultCode);
        }
    } finally {
        if (TracerSpanMap.containsKey(spanKey)) {
            TracerSpanMap.remove(spanKey);
        }
    }
    return result;
}
 
Example #20
Source File: DubboAppContextFilter.java    From dubbo-sentinel-support with Apache License 2.0 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
    if (application != null) {
        RpcContext.getContext().setAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, application);
    }
    return invoker.invoke(invocation);
}
 
Example #21
Source File: TracingFilter.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override protected String parseValue(Throwable input, TraceContext context) {
  if (!(input instanceof RpcException)) return null;
  return String.valueOf(((RpcException) input).getCode());
}
 
Example #22
Source File: FooServiceIT.java    From dubbo-samples with Apache License 2.0 4 votes vote down vote up
@Test(expected = RpcException.class)
public void testFlowControl2() throws Exception {
    for (int i = 0; i < 11; i++) {
        consumer.sayHello("dubbo");
    }
}
 
Example #23
Source File: TracingFilter.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
  if (!isInit) return invoker.invoke(invocation);
  TraceContext invocationContext = currentTraceContext.get();

  RpcContext rpcContext = RpcContext.getContext();
  Kind kind = rpcContext.isProviderSide() ? Kind.SERVER : Kind.CLIENT;
  Span span;
  DubboRequest request;
  if (kind.equals(Kind.CLIENT)) {
    // When A service invoke B service, then B service then invoke C service, the parentId of the
    // C service span is A when read from invocation.getAttachments(). This is because
    // AbstractInvoker adds attachments via RpcContext.getContext(), not the invocation.
    // See org.apache.dubbo.rpc.protocol.AbstractInvoker(line 141) from v2.7.3
    Map<String, String> attachments = RpcContext.getContext().getAttachments();
    DubboClientRequest clientRequest = new DubboClientRequest(invoker, invocation, attachments);
    request = clientRequest;
    span = clientHandler.handleSendWithParent(clientRequest, invocationContext);
  } else {
    DubboServerRequest serverRequest = new DubboServerRequest(invoker, invocation);
    request = serverRequest;
    span = serverHandler.handleReceive(serverRequest);
  }

  boolean isSynchronous = true;
  Scope scope = currentTraceContext.newScope(span.context());
  Result result = null;
  Throwable error = null;
  try {
    result = invoker.invoke(invocation);
    error = result.getException();
    CompletableFuture<Object> future = rpcContext.getCompletableFuture();
    if (future != null) {
      isSynchronous = false;
      // NOTE: We don't currently instrument CompletableFuture, so callbacks will not see the
      // invocation context unless they use an executor instrumented by CurrentTraceContext
      // If we later instrument this, take care to use the correct context depending on RPC kind!
      future.whenComplete(FinishSpan.create(this, request, result, span));
    }
    return result;
  } catch (Throwable e) {
    propagateIfFatal(e);
    error = e;
    throw e;
  } finally {
    if (isSynchronous) FinishSpan.finish(this, request, result, error, span);
    scope.close();
  }
}
 
Example #24
Source File: DubboHmilyTransactionFilter.java    From hmily with Apache License 2.0 4 votes vote down vote up
@Override
public Result invoke(final Invoker<?> invoker, final Invocation invocation) throws RpcException {
    String methodName = invocation.getMethodName();
    Class clazz = invoker.getInterface();
    Class[] args = invocation.getParameterTypes();
    final Object[] arguments = invocation.getArguments();
    Method method = null;
    Hmily hmily = null;
    try {
        converterParamsClass(args, arguments);
        method = clazz.getMethod(methodName, args);
        hmily = method.getAnnotation(Hmily.class);
    } catch (Exception ex) {
        LOGGER.error("hmily find method error {} ", ex);
    }
    if (Objects.nonNull(hmily)) {
        try {
            final HmilyTransactionContext hmilyTransactionContext = HmilyTransactionContextLocal.getInstance().get();
            if (Objects.nonNull(hmilyTransactionContext)) {
                RpcMediator.getInstance().transmit(RpcContext.getContext()::setAttachment, hmilyTransactionContext);
                final Result result = invoker.invoke(invocation);
                //if result has not exception
                if (!result.hasException()) {
                    final HmilyParticipant hmilyParticipant = buildParticipant(hmilyTransactionContext, hmily, method, clazz, arguments, args);
                    if (hmilyTransactionContext.getRole() == HmilyRoleEnum.INLINE.getCode()) {
                        hmilyTransactionExecutor.registerByNested(hmilyTransactionContext.getTransId(),
                                hmilyParticipant);
                    } else {
                        hmilyTransactionExecutor.enlistParticipant(hmilyParticipant);
                    }
                } else {
                    throw new HmilyRuntimeException("rpc invoke exception{}", result.getException());
                }
                return result;
            }
            return invoker.invoke(invocation);
        } catch (RpcException e) {
            e.printStackTrace();
            throw e;
        }
    } else {
        return invoker.invoke(invocation);
    }
}
 
Example #25
Source File: LogFilter.java    From dubbo-samples with Apache License 2.0 4 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    System.out.println(invocation.getMethodName() + "is invoked");
    return invoker.invoke(invocation);
}
 
Example #26
Source File: DemoServiceIT.java    From dubbo-samples with Apache License 2.0 4 votes vote down vote up
@Test(expected = RpcException.class)
public void testWithAppRuleWithInsufficientTimeout() throws Exception {
    ZKTools.generateApplicationLevelOverride(600);
    Thread.sleep(2000);
    demoService.sayHello("world", 1000);
}
 
Example #27
Source File: DemoServiceIT.java    From dubbo-samples with Apache License 2.0 4 votes vote down vote up
@Test(expected = RpcException.class)
public void testWithServiceRuleWithInsufficientTimeout() throws Exception {
    ZKTools.generateServiceLevelOverride(600);
    Thread.sleep(2000);
    demoService.sayHello("world", 1000);
}
 
Example #28
Source File: DemoServiceIT.java    From dubbo-samples with Apache License 2.0 4 votes vote down vote up
@Test(expected = RpcException.class)
public void testWithoutRule() throws Exception {
    Thread.sleep(2000);
    demoService.sayHello("world", 3000);
}
 
Example #29
Source File: DemoServiceIT.java    From dubbo-samples with Apache License 2.0 4 votes vote down vote up
@Test(expected = RpcException.class)
public void testDemoService3() throws Exception {
    RpcContext.getContext().setAttachment(TAG_KEY, "tag3");
    demoService.sayHello("world");
}
 
Example #30
Source File: TestClientFilter.java    From dubbo-samples with Apache License 2.0 4 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    return invoker.invoke(invocation);
}