本文整理了Java中io.grpc.Status
类的一些代码示例,展示了Status
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Status
类的具体详情如下:
包路径:io.grpc.Status
类名称:Status
[英]Defines the status of an operation by providing a standard Code in conjunction with an optional descriptive message. Instances of Status are created by starting with the template for the appropriate Status.Code and supplementing it with additional information: Status.NOT_FOUND.withDescription("Could not find 'important_file.txt'");
For clients, every remote call will return a status on completion. In the case of errors this status may be propagated to blocking stubs as a RuntimeException or to a listener as an explicit parameter.
Similarly servers can report a status by throwing StatusRuntimeExceptionor by passing the status to a callback.
Utility functions are provided to convert a status to an exception and to extract them back out.
[中]通过提供标准代码和可选的描述性消息来定义操作的状态。状态的实例是从相应状态的模板开始创建的。编码并用附加信息进行补充:状态。没有找到。withDescription(“找不到'important_file.txt'”;
对于客户端,每次远程调用都会在完成时返回一个状态。在出现错误的情况下,该状态可以作为RuntimeException传播到阻塞存根,或者作为显式参数传播到侦听器。
类似地,服务器可以通过抛出StatusRuntimeException或将状态传递给回调来报告状态。
提供了实用程序函数,用于将状态转换为异常并将其提取出来。
代码示例来源:origin: AxonFramework/AxonFramework
@Override
public void onError(Throwable ex) {
logger.warn("Received error from server: {}", ex.getMessage());
outboundStreamObserver = null;
if (ex instanceof StatusRuntimeException && ((StatusRuntimeException) ex).getStatus().getCode().equals(Status.UNAVAILABLE.getCode())) {
return;
}
resubscribe();
}
代码示例来源:origin: apache/avro
@Override
public Object[] parse(InputStream stream) {
try {
BinaryDecoder in = DECODER_FACTORY.binaryDecoder(stream, null);
Schema reqSchema = message.getRequest();
GenericRecord request = (GenericRecord) new SpecificDatumReader<>(reqSchema).read(null, in);
Object[] args = new Object[reqSchema.getFields().size()];
int i = 0;
for (Schema.Field field : reqSchema.getFields()) {
args[i++] = request.get(field.name());
}
return args;
} catch (IOException e) {
throw Status.INTERNAL.withCause(e).
withDescription("Error deserializing avro request arguments").asRuntimeException();
} finally {
AvroGrpcUtils.skipAndCloseQuietly(stream);
}
}
代码示例来源: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
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 onError(Throwable t) {
Metadata metadata = Status.trailersFromThrowable(t);
if (metadata == null) {
metadata = new Metadata();
}
if (t instanceof MotanBizException) {
call.close(Status.INTERNAL.withDescription(t.getMessage()).withCause(t), metadata);
} else {
call.close(Status.UNAVAILABLE.withDescription(t.getMessage()).withCause(t), metadata);
}
}
代码示例来源:origin: Alluxio/alluxio
@Override
public void onNext(SaslMessage saslMessage) {
try {
SaslMessage response = mSaslHandshakeClientHandler.handleSaslMessage(saslMessage);
if (response == null) {
mRequestObserver.onCompleted();
} else {
mRequestObserver.onNext(response);
}
} catch (SaslException e) {
mAuthenticated.setException(e);
mRequestObserver
.onError(Status.fromCode(Status.Code.UNAUTHENTICATED).withCause(e).asException());
}
}
代码示例来源:origin: yidongnan/grpc-spring-boot-starter
/**
* Close the call with {@link Status#UNAUTHENTICATED}.
*
* @param call The call to close.
* @param aex The exception that was the cause.
*/
protected void closeCallUnauthenticated(final ServerCall<?, ?> call, final AuthenticationException aex) {
call.close(Status.UNAUTHENTICATED.withCause(aex).withDescription(UNAUTHENTICATED_DESCRIPTION), new Metadata());
}
代码示例来源:origin: line/armeria
@Test
public void error_withMessage() throws Exception {
final StatusRuntimeException t = (StatusRuntimeException) catchThrowable(
() -> blockingClient.errorWithMessage(REQUEST_MESSAGE));
assertThat(t.getStatus().getCode()).isEqualTo(Code.ABORTED);
assertThat(t.getStatus().getDescription()).isEqualTo("aborted call");
checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
assertThat(rpcReq.method()).isEqualTo("armeria.grpc.testing.UnitTestService/ErrorWithMessage");
assertThat(rpcReq.params()).containsExactly(REQUEST_MESSAGE);
assertThat(grpcStatus).isNotNull();
assertThat(grpcStatus.getCode()).isEqualTo(Code.ABORTED);
assertThat(grpcStatus.getDescription()).isEqualTo("aborted call");
});
}
代码示例来源:origin: Netflix/conductor
Metadata metadata = new Metadata();
metadata.put(STATUS_DETAILS_KEY,
DebugInfo.newBuilder()
.addAllStackEntries(Arrays.asList(frames))
.withDescription(t.getMessage())
.withCause(t)
.asException(metadata);
代码示例来源: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: com.impetus.fabric/fabric-jdbc-driver-shaded
@Override
public void onCompleted() {
if (cancelled) {
throw Status.CANCELLED.withDescription("call already cancelled").asRuntimeException();
} else {
call.close(Status.OK, new Metadata());
}
}
代码示例来源:origin: line/armeria
final Status s = Status.fromThrowable(t);
if (s.getCode() != Code.UNKNOWN) {
return s;
return Status.UNKNOWN.withCause(t);
return Status.UNAVAILABLE.withCause(t);
return Status.INTERNAL.withCause(t);
return Status.DEADLINE_EXCEEDED.withCause(t);
代码示例来源:origin: line/armeria
@Override
public void errorWithMessage(SimpleRequest request, StreamObserver<SimpleResponse> responseObserver) {
responseObserver.onError(Status.ABORTED.withDescription("aborted call").asException());
}
代码示例来源:origin: Alluxio/alluxio
switch (Status.fromThrowable(e).getCode()) {
case ABORTED:
alluxioStatus = alluxio.exception.status.Status.ABORTED;
if (e.getTrailers() != null && e.getTrailers().containsKey(sInnerCauseKey)) {
try {
cause = (Throwable) SerializationUtils.deserialize(e.getTrailers().get(sInnerCauseKey));
} catch (Exception exc) {
LOG.warn("Failed to deserialize the cause: {}", exc);
代码示例来源:origin: googleapis/google-cloud-java
@Test
public void resourceExhaustedWithBackoff() {
Status status =
Status.fromCodeValue(Status.Code.RESOURCE_EXHAUSTED.value())
.withDescription("Memory pushback");
Metadata trailers = new Metadata();
Metadata.Key<RetryInfo> key = ProtoUtils.keyForProto(RetryInfo.getDefaultInstance());
RetryInfo retryInfo =
RetryInfo.newBuilder()
.setRetryDelay(Duration.newBuilder().setNanos(1000000).setSeconds(1L))
.build();
trailers.put(key, retryInfo);
SpannerException e =
SpannerExceptionFactory.newSpannerException(new StatusRuntimeException(status, trailers));
assertThat(e.isRetryable()).isTrue();
assertThat(e.getRetryDelayInMillis()).isEqualTo(1001);
}
代码示例来源:origin: line/armeria
.withDescription("Unknown: " + req.getResponseCompression())
.asRuntimeException());
return;
.withDescription("compression not supported.")
.withCause(e)
.asRuntimeException());
return;
obs.onError(Status.fromCodeValue(req.getResponseStatus().getCode())
.withDescription(req.getResponseStatus().getMessage())
.asRuntimeException());
return;
代码示例来源:origin: googleapis/google-cloud-java
requestParamsHeader.put(requestParamsKey, "name=" + kmsKeyRingResourcePath);
KeyManagementServiceBlockingStub stubForGetKeyRing =
MetadataUtils.attachHeaders(kmsStub, requestParamsHeader);
stubForGetKeyRing.getKeyRing(getKeyRingRequest);
} catch (StatusRuntimeException ex) {
if (ex.getStatus().getCode() == Status.Code.NOT_FOUND) {
.setKeyRingId(keyRingName)
.build();
requestParamsHeader.put(requestParamsKey, "parent=" + keyRingParent);
KeyManagementServiceBlockingStub stubForCreateKeyRing =
MetadataUtils.attachHeaders(kmsStub, requestParamsHeader);
代码示例来源:origin: saturnism/grpc-java-by-example
@Override
public void customException(EchoRequest request, StreamObserver<EchoResponse> responseObserver) {
try {
throw new CustomException("Custom exception!");
} catch (Exception e) {
responseObserver.onError(Status.INTERNAL
.withDescription(e.getMessage())
.augmentDescription("customException()")
.withCause(e) // This can be attached to the Status locally, but NOT transmitted to the client!
.asRuntimeException());
}
}
代码示例来源:origin: Alluxio/alluxio
Metadata trailers = new Metadata();
trailers.put(sInnerCauseKey, SerializationUtils.serialize(cause));
} catch (Exception exc) {
LOG.warn("Could not serialize the cause: {}. Failed with: {}", cause, exc);
return Status.fromCode(code).asException(trailers);
代码示例来源:origin: line/armeria
assertThat(t).isInstanceOf(StatusRuntimeException.class);
final StatusRuntimeException e = (StatusRuntimeException) t;
assertThat(e.getStatus().getCode()).isEqualTo(Status.UNKNOWN.getCode());
assertThat(e.getStatus().getDescription()).isEqualTo(errorMessage);
assertThat(Status.fromThrowable(captor.getValue()).getCode()).isEqualTo(Status.UNKNOWN.getCode());
assertThat(Status.fromThrowable(captor.getValue()).getDescription()).isEqualTo(errorMessage);
verifyNoMoreInteractions(responseObserver);
assertThat(rpcReq.params()).containsExactly(simpleRequest);
assertThat(grpcStatus).isNotNull();
assertThat(grpcStatus.getCode()).isEqualTo(Code.UNKNOWN);
assertThat(grpcStatus.getDescription()).isEqualTo(errorMessage);
});
内容来源于网络,如有侵权,请联系作者删除!