io.grpc.Status.fromThrowable()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(11.0k)|赞(0)|评价(0)|浏览(161)

本文整理了Java中io.grpc.Status.fromThrowable()方法的一些代码示例,展示了Status.fromThrowable()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Status.fromThrowable()方法的具体详情如下:
包路径:io.grpc.Status
类名称:Status
方法名:fromThrowable

Status.fromThrowable介绍

[英]Extract an error Status from the causal chain of a Throwable. If no status can be found, a status is created with Code#UNKNOWN as its code and t as its cause.
[中]从一次性物品的因果链中提取错误状态。如果找不到状态,则创建状态,代码为#未知,原因为t。

代码示例

代码示例来源:origin: apache/incubator-shardingsphere

@Override
  public void onError(final Throwable cause) {
    log.warn("Keep alive failed, due to {}, renew it", Status.fromThrowable(cause));
    heartbeat(leaseId);
  }
};

代码示例来源:origin: line/armeria

private void invokeOnReady() {
  try {
    listener.onReady();
  } catch (Throwable t) {
    close(Status.fromThrowable(t), EMPTY_METADATA);
  }
}

代码示例来源:origin: line/armeria

private void invokeOnMessage(I request) {
  try (SafeCloseable ignored = ctx.push()) {
    listener.onMessage(request);
  } catch (Throwable t) {
    close(Status.fromThrowable(t), EMPTY_METADATA);
  }
}

代码示例来源:origin: line/armeria

private void invokeHalfClose() {
  try (SafeCloseable ignored = ctx.push()) {
    listener.onHalfClose();
  } catch (Throwable t) {
    close(Status.fromThrowable(t), EMPTY_METADATA);
  }
}

代码示例来源:origin: line/armeria

private void invokeOnCancel() {
  try (SafeCloseable ignored = ctx.push()) {
    listener.onCancel();
  } catch (Throwable t) {
    if (!closeCalled) {
      // A custom error when dealing with client cancel or transport issues should be
      // returned. We have already closed the listener, so it will not receive any more
      // callbacks as designed.
      close(Status.fromThrowable(t), EMPTY_METADATA);
    }
  }
}

代码示例来源:origin: googleapis/google-cloud-java

ApiException gaxException =
  ApiExceptionFactory.createException(
    cause, GrpcStatusCode.of(Status.fromThrowable(cause).getCode()), false);
logger.log(Level.SEVERE, "terminated streaming with exception", gaxException);
notifyFailed(gaxException);

代码示例来源:origin: vert-x3/vertx-examples

/**
 * Async client-streaming example. Sends {@code numPoints} randomly chosen points from {@code
 * features} with a variable delay in between. Prints the statistics when they are sent from the
 * server.
 */
public void recordRoute(List<Feature> features, int numPoints) throws InterruptedException {
 System.out.println("*** RecordRoute");
 stub.recordRoute(exchange -> {
  RouteSender sender = new RouteSender(features, exchange);
  exchange.handler(ar -> {
   sender.result = ar;
   if (ar.succeeded()) {
    RouteSummary summary = ar.result();
    System.out.println("Finished trip with " + summary.getPointCount() + " points. Passed " + summary.getFeatureCount()
     + " features.Travelled " + summary.getDistance() + " meters. It took " + summary.getElapsedTime() + " seconds.");
    System.out.println("Finished RecordRoute");
   } else {
    System.out.println("RecordRoute Failed: " + Status.fromThrowable(ar.cause()));
   }
  });
  // Send numPoints points randomly selected from the features list.
  sender.send(numPoints);
 });
}

代码示例来源:origin: line/armeria

private void doSendMessage(O message) {
  checkState(sendHeadersCalled, "sendHeaders has not been called");
  checkState(!closeCalled, "call is closed");
  if (firstResponse == null) {
    firstResponse = message;
  }
  try {
    res.write(messageFramer.writePayload(marshaller.serializeResponse(message)));
    res.onDemand(() -> {
      if (pendingMessagesUpdater.decrementAndGet(this) == 0) {
        if (useBlockingTaskExecutor) {
          ctx.blockingTaskExecutor().execute(this::invokeOnReady);
        } else {
          invokeOnReady();
        }
      }
    });
  } catch (RuntimeException e) {
    close(Status.fromThrowable(e), EMPTY_METADATA);
    throw e;
  } catch (Throwable t) {
    close(Status.fromThrowable(t), EMPTY_METADATA);
    throw new RuntimeException(t);
  }
}

代码示例来源:origin: googleapis/google-cloud-java

/**
 * Creates a new exception based on {@code cause}. If {@code cause} indicates cancellation, {@code
 * context} will be inspected to establish the type of cancellation.
 *
 * <p>Intended for internal library use; user code should use {@link
 * #newSpannerException(ErrorCode, String)} instead of this method.
 */
public static SpannerException newSpannerException(@Nullable Context context, Throwable cause) {
 if (cause instanceof SpannerException) {
  SpannerException e = (SpannerException) cause;
  return newSpannerExceptionPreformatted(e.getErrorCode(), e.getMessage(), e);
 } else if (cause instanceof CancellationException) {
  return newSpannerExceptionForCancellation(context, cause);
 }
 // Extract gRPC status.  This will produce "UNKNOWN" for non-gRPC exceptions.
 Status status = Status.fromThrowable(cause);
 if (status.getCode() == Status.Code.CANCELLED) {
  return newSpannerExceptionForCancellation(context, cause);
 }
 return newSpannerException(ErrorCode.fromGrpcStatus(status), cause.getMessage(), cause);
}

代码示例来源:origin: line/armeria

/**
 * Dispatches the current response chunk to the client. This is only called by the executor. At
 * any time, a given dispatch task should only be registered with the executor once.
 */
private synchronized void dispatchChunk() {
  if (cancelled) {
    return;
  }
  try {
    // Pop off the next chunk and send it to the client.
    Chunk chunk = chunks.remove();
    if (chunk == completionChunk) {
      responseStream.onCompleted();
    } else {
      responseStream.onNext(chunk.toResponse());
    }
  } catch (Throwable e) {
    failure = e;
    if (Status.fromThrowable(e).getCode() == Status.CANCELLED.getCode()) {
      // Stream was cancelled by client, responseStream.onError() might be called already or
      // will be called soon by inbounding StreamObserver.
      chunks.clear();
    } else {
      responseStream.onError(e);
    }
  }
}

代码示例来源:origin: line/armeria

final Status s = Status.fromThrowable(t);
if (s.getCode() != Code.UNKNOWN) {
  return s;

代码示例来源:origin: line/armeria

@Override
public void messageRead(ByteBufOrStream message) {
  try {
    final O msg = marshaller.deserializeResponse(message);
    if (firstResponse == null) {
      firstResponse = msg;
    }
    if (unsafeWrapResponseBuffers && message.buf() != null) {
      GrpcUnsafeBufferUtil.storeBuffer(message.buf(), msg, ctx);
    }
    try (SafeCloseable ignored = ctx.push()) {
      listener.onMessage(msg);
    }
  } catch (Throwable t) {
    req.close(Status.fromThrowable(t).asException());
    throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
  }
}

代码示例来源:origin: line/armeria

} catch (Throwable t) {
  call.setListener(new EmptyListener<>());
  call.close(Status.fromThrowable(t), EMPTY_METADATA);
  logger.warn(
      "Exception thrown from streaming request stub method before processing any request data" +

代码示例来源:origin: line/armeria

@Test
public void cancelAfterBegin() throws Exception {
  final StreamRecorder<StreamingInputCallResponse> responseObserver = StreamRecorder.create();
  final StreamObserver<StreamingInputCallRequest> requestObserver =
      asyncStub.streamingInputCall(responseObserver);
  requestObserver.onError(new RuntimeException());
  responseObserver.awaitCompletion();
  assertThat(responseObserver.getValues()).isEmpty();
  assertThat(Status.fromThrowable(responseObserver.getError()).getCode()).isEqualTo(Code.CANCELLED);
  final RequestLog log = requestLogQueue.take();
  assertThat(log.availabilities()).contains(RequestLogAvailability.COMPLETE);
  assertThat(log.responseContent()).isInstanceOf(RpcResponse.class);
  final Throwable cause = ((RpcResponse) log.responseContent()).cause();
  assertThat(cause).isInstanceOf(StatusException.class);
  assertThat(((StatusException) cause).getStatus().getCode()).isEqualTo(Code.CANCELLED);
}

代码示例来源:origin: vert-x3/vertx-examples

/**
 * Bi-directional example, which can only be asynchronous. Send some chat messages, and print any
 * chat messages that are sent from the server.
 */
public void routeChat() {
 System.out.println("*** RouteChat");
 stub.routeChat(exchange -> {
  exchange.handler(note -> {
   System.out.println("Got message \"" + note.getMessage() + "\" at " + note.getLocation().getLatitude() +
    ", " + note.getLocation().getLongitude());
  });
  exchange.exceptionHandler(err -> {
   System.out.println("RouteChat Failed: " + Status.fromThrowable(err));
  });
  exchange.endHandler(v -> {
   System.out.println("Finished RouteChat");
  });
  RouteNote[] requests =
   {newNote("First message", 0, 0), newNote("Second message", 0, 1),
    newNote("Third message", 1, 0), newNote("Fourth message", 1, 1)};
  for (RouteNote request : requests) {
   System.out.println("Sending message \"" + request.getMessage() + "\" at " + request.getLocation()
    .getLatitude() + ", " + request.getLocation().getLongitude());
   exchange.write(request);
  }
  exchange.end();
 });
}

代码示例来源:origin: line/armeria

assertThat(Status.fromThrowable(captor.getValue()).getCode()).isEqualTo(Status.UNKNOWN.getCode());
assertThat(Status.fromThrowable(captor.getValue()).getDescription()).isEqualTo(errorMessage);
verifyNoMoreInteractions(responseObserver);

代码示例来源:origin: line/armeria

@Test
public void cancelAfterFirstResponse() throws Exception {
  final StreamingOutputCallRequest request =
      StreamingOutputCallRequest.newBuilder()
                   .addResponseParameters(ResponseParameters.newBuilder()
                                        .setSize(31415))
                   .setPayload(Payload.newBuilder()
                             .setBody(ByteString.copyFrom(new byte[27182])))
                   .build();
  final StreamingOutputCallResponse goldenResponse =
      StreamingOutputCallResponse.newBuilder()
                    .setPayload(Payload.newBuilder()
                             .setType(COMPRESSABLE)
                             .setBody(ByteString.copyFrom(new byte[31415])))
                    .build();
  final StreamRecorder<StreamingOutputCallResponse> responseObserver = StreamRecorder.create();
  final StreamObserver<StreamingOutputCallRequest> requestObserver
      = asyncStub.fullDuplexCall(responseObserver);
  requestObserver.onNext(request);
  await().untilAsserted(() -> assertThat(responseObserver.firstValue().get()).isEqualTo(goldenResponse));
  requestObserver.onError(new RuntimeException());
  responseObserver.awaitCompletion(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
  assertThat(responseObserver.getValues()).hasSize(1);
  assertThat(Status.fromThrowable(responseObserver.getError()).getCode()).isEqualTo(Code.CANCELLED);
  checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
    assertThat(rpcReq.params()).containsExactly(request);
    assertThat(grpcStatus.getCode()).isEqualTo(Code.CANCELLED);
  });
}

代码示例来源:origin: line/armeria

@Override
public void start(Listener<O> responseListener, Metadata unused) {
  requireNonNull(responseListener, "responseListener");
  final Compressor compressor;
  if (callOptions.getCompressor() != null) {
    compressor = compressorRegistry.lookupCompressor(callOptions.getCompressor());
    if (compressor == null) {
      responseListener.onClose(
          Status.INTERNAL.withDescription(
              "Unable to find compressor by name " + callOptions.getCompressor()),
          EMPTY_METADATA);
      return;
    }
  } else {
    compressor = Identity.NONE;
  }
  messageFramer.setCompressor(compressor);
  prepareHeaders(req.headers(), compressor);
  listener = responseListener;
  final HttpResponse res;
  try (SafeCloseable ignored = ctx.push()) {
    res = httpClient.execute(ctx, req);
  } catch (Exception e) {
    close(Status.fromThrowable(e));
    return;
  }
  res.subscribe(responseReader, ctx.eventLoop(), true);
  res.completionFuture().handleAsync(responseReader, ctx.eventLoop());
}

代码示例来源:origin: line/armeria

private void doSendMessage(I message) {
  try {
    if (!ctx.log().isAvailable(RequestLogAvailability.REQUEST_CONTENT)) {
      ctx.logBuilder().requestContent(GrpcLogUtil.rpcRequest(method, message), null);
    }
    final ByteBuf serialized = marshaller.serializeRequest(message);
    req.write(messageFramer.writePayload(serialized));
    req.onDemand(() -> {
      if (pendingMessagesUpdater.decrementAndGet(this) == 0) {
        try (SafeCloseable ignored = ctx.push()) {
          listener.onReady();
        } catch (Throwable t) {
          close(Status.fromThrowable(t));
        }
      }
    });
  } catch (Throwable t) {
    cancel(null, t);
  }
}

代码示例来源:origin: line/armeria

assertThat(Status.fromThrowable(recorder.getError()).getCode())
    .isEqualTo(Status.DEADLINE_EXCEEDED.getCode());

相关文章