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

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

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

Status.asRuntimeException介绍

[英]Convert this Status to a RuntimeException. Use #fromThrowableto recover this Status instance when the returned exception is in the causal chain.
[中]将此状态转换为RuntimeException。当返回的异常位于因果链中时,使用#fromThrowable恢复此状态实例。

代码示例

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

private void verifySize() {
    if (count > maxMessageSize) {
      throw Status.RESOURCE_EXHAUSTED.withDescription(String.format(
          "%s: Compressed frame exceeds maximum frame size: %d. Bytes read: %d. ",
          debugString, maxMessageSize, count)).asRuntimeException();
    }
  }
}

代码示例来源:origin: weibocom/motan

@Override
public void onCompleted() {
  if (cancelled) {
    throw Status.CANCELLED.asRuntimeException();
  } else {
    call.close(Status.OK, new Metadata());
  }
}

代码示例来源:origin: weibocom/motan

@Override
public void onNext(RespT response) {
  if (cancelled) {
    throw Status.CANCELLED.asRuntimeException();
  }
  if (!sentHeaders) {
    call.sendHeaders(new Metadata());
    sentHeaders = true;
  }
  //TODO send header from here..
  call.sendMessage(response);
}

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

@Override
public StreamObserver<SimpleRequest> streamThrowsErrorInStub(
    StreamObserver<SimpleResponse> responseObserver) {
  throw Status.ABORTED.withDescription("bad streaming stub").asRuntimeException();
}

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

@Override
public void unaryThrowsError(SimpleRequest request, StreamObserver<SimpleResponse> responseObserver) {
  throw Status.ABORTED.withDescription("call aborted").asRuntimeException();
}

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

@Override
public void onNext(SimpleRequest value) {
  throw Status.ABORTED.withDescription("bad streaming message").asRuntimeException();
}

代码示例来源:origin: Netflix/concurrency-limits

@Override
  public void invoke(String req, StreamObserver<String> observer) {
    try {
      long delay = builder.segments.get(0).latency();
      semaphore.acquire();
      TimeUnit.MILLISECONDS.sleep(delay);
      observer.onNext("response");
      observer.onCompleted();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      observer.onError(Status.UNKNOWN.asRuntimeException());
    } finally {
      semaphore.release();
    }
  }
});

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

@Override
  public void unaryCall(SimpleRequest request, StreamObserver<SimpleResponse> responseObserver) {
    IllegalStateException e1 = new IllegalStateException("Exception 1");
    IllegalArgumentException e2 = new IllegalArgumentException();
    AssertionError e3 = new AssertionError("Exception 3");
    Exceptions.clearTrace(e3);
    RuntimeException e4 = new RuntimeException("Exception 4");
    e1.initCause(e2);
    e2.initCause(e3);
    e3.initCause(e4);
    Status status = Status.ABORTED.withCause(e1);
    responseObserver.onError(status.asRuntimeException());
  }
}

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

private ByteBufOrStream getCompressedBody(ByteBuf buf) {
  if (decompressor == Codec.Identity.NONE) {
    buf.release();
    throw Status.INTERNAL.withDescription(
        DEBUG_STRING + ": Can't decode compressed frame as compression not configured.")
               .asRuntimeException();
  }
  try {
    // Enforce the maxMessageSizeBytes limit on the returned stream.
    final InputStream unlimitedStream =
        decompressor.decompress(new ByteBufInputStream(buf, true));
    return new ByteBufOrStream(
        new SizeEnforcingInputStream(unlimitedStream, maxMessageSizeBytes, DEBUG_STRING));
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: Netflix/conductor

@Override
public void batchPoll(TaskServicePb.BatchPollRequest req, StreamObserver<TaskPb.Task> response) {
  final int count = GRPC_HELPER.optionalOr(req.getCount(), 1);
  final int timeout = GRPC_HELPER.optionalOr(req.getTimeout(), POLL_TIMEOUT_MS);
  if (timeout > MAX_POLL_TIMEOUT_MS) {
    response.onError(Status.INVALID_ARGUMENT
        .withDescription("longpoll timeout cannot be longer than " + MAX_POLL_TIMEOUT_MS + "ms")
        .asRuntimeException()
    );
    return;
  }
  try {
    List<Task> polledTasks = taskService.batchPoll(req.getTaskType(), req.getWorkerId(),
        GRPC_HELPER.optional(req.getDomain()), count, timeout);
    LOGGER.info("polled tasks: "+polledTasks);
    polledTasks.stream().map(PROTO_MAPPER::toProto).forEach(response::onNext);
    response.onCompleted();
  } catch (Exception e) {
    GRPC_HELPER.onError(response, e);
  }
}

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

/** Convert an entry's status from a protobuf to an {@link ApiException}. */
private ApiException createEntryError(com.google.rpc.Status protoStatus) {
 io.grpc.Status grpcStatus =
   io.grpc.Status.fromCodeValue(protoStatus.getCode())
     .withDescription(protoStatus.getMessage());
 StatusCode gaxStatusCode = GrpcStatusCode.of(grpcStatus.getCode());
 return ApiExceptionFactory.createException(
   grpcStatus.asRuntimeException(),
   gaxStatusCode,
   retryableCodes.contains(gaxStatusCode.getCode()));
}

代码示例来源:origin: Netflix/conductor

@Override
public void getTask(MetadataServicePb.GetTaskRequest req, StreamObserver<MetadataServicePb.GetTaskResponse> response) {
  TaskDef def = service.getTaskDef(req.getTaskType());
  if (def != null) {
    TaskDefPb.TaskDef task = PROTO_MAPPER.toProto(def);
    response.onNext(MetadataServicePb.GetTaskResponse.newBuilder()
        .setTask(task)
        .build()
    );
    response.onCompleted();
  } else {
    response.onError(Status.NOT_FOUND
        .withDescription("No such TaskDef found by taskType=" + req.getTaskType())
        .asRuntimeException()
    );
  }
}

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

@Test
public void onMessage_deframeError_errorListenerThrows() {
  doThrow(Status.INTERNAL.asRuntimeException())
      .when(deframer).deframe(isA(HttpData.class), anyBoolean());
  doThrow(new IllegalStateException())
      .when(transportStatusListener).transportReportStatus(isA(Status.class));
  reader.onSubscribe(subscription);
  assertThatThrownBy(() -> reader.onNext(DATA)).isInstanceOf(IllegalStateException.class);
  verify(deframer).close();
}

代码示例来源:origin: Alluxio/alluxio

/**
 * Checks expected error during receive.
 */
@Test
public void receiveError() throws Exception {
 mThrown.expect(UnauthenticatedException.class);
 mThrown.expectMessage(containsString(TEST_MESSAGE));
 mResponseObserver.onError(Status.UNAUTHENTICATED.asRuntimeException());
 mStream.receive(TIMEOUT);
}

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

@Test
public void onMessage_deframeError() {
  doThrow(Status.INTERNAL.asRuntimeException())
      .when(deframer).deframe(isA(HttpData.class), anyBoolean());
  reader.onSubscribe(subscription);
  reader.onNext(DATA);
  verify(deframer).deframe(DATA, false);
  verify(transportStatusListener).transportReportStatus(Status.INTERNAL);
  verify(deframer).close();
}

代码示例来源:origin: Netflix/conductor

@Override
public void getWorkflow(MetadataServicePb.GetWorkflowRequest req, StreamObserver<MetadataServicePb.GetWorkflowResponse > response) {
  try {
    WorkflowDef workflowDef = service.getWorkflowDef(req.getName(), GRPC_HELPER.optional(req.getVersion()));
    WorkflowDefPb.WorkflowDef workflow = PROTO_MAPPER.toProto(workflowDef);
    response.onNext(MetadataServicePb.GetWorkflowResponse.newBuilder()
        .setWorkflow(workflow)
        .build()
    );
    response.onCompleted();
  } catch (ApplicationException e) {
    // TODO replace this with gRPC exception interceptor.
    response.onError(Status.NOT_FOUND
        .withDescription("No such workflow found by name=" + req.getName())
        .asRuntimeException()
    );
  }
}

代码示例来源:origin: Alluxio/alluxio

/**
 * Checks expected error during send.
 */
@Test
public void sendError() throws Exception {
 mThrown.expect(UnauthenticatedException.class);
 mThrown.expectMessage(containsString(TEST_MESSAGE));
 mResponseObserver.onError(Status.UNAUTHENTICATED.asRuntimeException());
 mStream.send(WriteRequest.newBuilder().build(), TIMEOUT);
}

代码示例来源:origin: Alluxio/alluxio

/**
 * Checks receive fails immediately upon error even if buffer is full.
 */
@Test
public void receiveErrorWhenBufferFull() throws Exception {
 mThrown.expect(UnauthenticatedException.class);
 mThrown.expectMessage(containsString(TEST_MESSAGE));
 WriteResponse[] responses = Stream.generate(() -> WriteResponse.newBuilder().build())
   .limit(BUFFER_SIZE).toArray(WriteResponse[]::new);
 for (WriteResponse response : responses) {
  mResponseObserver.onNext(response);
 }
 mResponseObserver.onError(Status.UNAUTHENTICATED.asRuntimeException());
 for (WriteResponse response : responses) {
  WriteResponse actualResponse = mStream.receive(TIMEOUT);
  Assert.assertEquals(response, actualResponse);
 }
}

代码示例来源:origin: Netflix/concurrency-limits

@Test
public void releaseOnError() {
  // Setup server
  final Server server = startServer((req, observer) -> {
    observer.onError(Status.INVALID_ARGUMENT.asRuntimeException());
  });
  // Make Client call
  final Channel channel = NettyChannelBuilder.forAddress("localhost", server.getPort())
      .usePlaintext(true)
      .build();
  try {
    ClientCalls.blockingUnaryCall(channel, METHOD_DESCRIPTOR, CallOptions.DEFAULT, "foo");
    Assert.fail("Should have failed with UNKNOWN error");
  } catch (StatusRuntimeException e) {
    // Verify
    Assert.assertEquals(Status.Code.INVALID_ARGUMENT, e.getStatus().getCode());
    Mockito.verify(limiter, Mockito.times(1)).acquire(Mockito.isA(GrpcServerRequestContext.class));
    Mockito.verify(listener, Mockito.times(1)).onIgnore();
  }
}

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

@Override
public void onNext(StreamingOutputCallRequest request) {
  if (request.hasResponseStatus()) {
    dispatcher.cancel();
    responseObserver.onError(Status.fromCodeValue(request.getResponseStatus().getCode())
                    .withDescription(
                        request.getResponseStatus().getMessage())
                    .asRuntimeException());
    return;
  }
  dispatcher.enqueue(toChunkQueue(request));
}

相关文章