/** Extracts the GRPC status code if available. Returns UNKNOWN for non-GRPC exceptions. */ private static Status getStatus(Throwable throwable) { Status status = Status.UNKNOWN; if (throwable instanceof StatusRuntimeException) { status = ((StatusRuntimeException) throwable).getStatus(); } else if (throwable instanceof StatusException) { status = ((StatusException) throwable).getStatus(); } return status; }
@Override public synchronized void onCompleted() { maybeReopenStream(new StatusException(Status.fromCode(Code.UNKNOWN))); }
final Throwable cause = statusException.getCause(); if (cause != null) { res.close(cause);
/** * Executes a function on a {@code StatusException} or a {@code StatusRuntimeException}, passing in the exception's * metadata and trailers. * * @param t a {@code StatusException} or a {@code StatusRuntimeException} * @param function the function to execute, given the exception's status and trailers * @param <T> the function's return type * * @throws IllegalArgumentException if {@code t} is not a {@code StatusException} or a {@code StatusRuntimeException} */ public static <T> T doWithStatus(Throwable t, BiFunction<Status, Metadata, T> function) { if (t instanceof StatusException) { return function.apply(((StatusException) t).getStatus(), ((StatusException) t).getTrailers()); } if (t instanceof StatusRuntimeException) { return function.apply(((StatusRuntimeException) t).getStatus(), ((StatusRuntimeException) t).getTrailers()); } throw new IllegalArgumentException("Throwable " + t.getClass().getSimpleName() + " is neither a " + "StatusException nor a StatusRuntimeException"); } }
private static void logExceptions(RetriesExhaustedWithDetailsException e) { System.out.println(e.getExhaustiveDescription()); Set<String> codes = new TreeSet<>(); Set<String> messages = new TreeSet<>(); for (Throwable e1 : e.getCauses()) { if (e1 instanceof StatusException) { StatusException statusException = (StatusException) e1; codes.add(statusException.getStatus().getCode().name()); messages.add(statusException.getMessage()); } } } }
/** * Extract an error trailers from the causal chain of a {@link Throwable}. * * @return the trailers or {@code null} if not found. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4683") public static Metadata trailersFromThrowable(Throwable t) { Throwable cause = checkNotNull(t, "t"); while (cause != null) { if (cause instanceof StatusException) { return ((StatusException) cause).getTrailers(); } else if (cause instanceof StatusRuntimeException) { return ((StatusRuntimeException) cause).getTrailers(); } cause = cause.getCause(); } return null; }
/** * Executes a function on a {@code StatusException} or a {@code StatusRuntimeException}, passing in the exception's * metadata and trailers. * * @param t a {@code StatusException} or a {@code StatusRuntimeException} * @param function the function to execute, given the exception's status and trailers * @param <T> the function's return type * * @throws IllegalArgumentException if {@code t} is not a {@code StatusException} or a {@code StatusRuntimeException} */ public static <T> T doWithStatus(Throwable t, BiFunction<Status, Metadata, T> function) { if (t instanceof StatusException) { return function.apply(((StatusException) t).getStatus(), ((StatusException) t).getTrailers()); } if (t instanceof StatusRuntimeException) { return function.apply(((StatusRuntimeException) t).getStatus(), ((StatusRuntimeException) t).getTrailers()); } throw new IllegalArgumentException("Throwable " + t.getClass().getSimpleName() + " is neither a " + "StatusException nor a StatusRuntimeException"); } }
/** * Extract an error trailers from the causal chain of a {@link Throwable}. * * @return the trailers or {@code null} if not found. */ @ExperimentalApi public static Metadata trailersFromThrowable(Throwable t) { Throwable cause = checkNotNull(t, "t"); while (cause != null) { if (cause instanceof StatusException) { return ((StatusException) cause).getTrailers(); } else if (cause instanceof StatusRuntimeException) { return ((StatusRuntimeException) cause).getTrailers(); } cause = cause.getCause(); } return null; }
private static void assertResponseTimeoutExceptionOrDeadlineExceeded(@Nullable Throwable cause) { assertThat(cause).isNotNull(); // Both exceptions can be raised when a timeout occurs due to timing issues, // and the first triggered one wins. if (cause instanceof ResponseTimeoutException) { return; } if (cause instanceof StatusException) { assertThat(((StatusException) cause).getStatus().getCode()).isEqualTo(Code.DEADLINE_EXCEEDED); return; } fail("cause must be a ResponseTimeoutException or a StatusException: ", cause); }
/** * Extract a {@link com.google.rpc.Status} instance from the causal chain of a {@link Throwable}. * * @return the extracted {@link com.google.rpc.Status} instance, or {@code null} if none exists. * @throws IllegalArgumentException if an embedded {@link com.google.rpc.Status} is found and its * code does not match the gRPC {@link Status} code. * @since 1.3.0 */ @Nullable public static com.google.rpc.Status fromThrowable(Throwable t) { Throwable cause = checkNotNull(t, "t"); while (cause != null) { if (cause instanceof StatusException) { StatusException e = (StatusException) cause; return fromStatusAndTrailers(e.getStatus(), e.getTrailers()); } else if (cause instanceof StatusRuntimeException) { StatusRuntimeException e = (StatusRuntimeException) cause; return fromStatusAndTrailers(e.getStatus(), e.getTrailers()); } cause = cause.getCause(); } return null; }
private void destroy(Code code) throws InterruptedException { streamObserverCapture.getValue().onError(new StatusException(io.grpc.Status.fromCode(code))); }
final Throwable cause = statusException.getCause(); if (cause != null) { res.close(cause);
private static void checkRequestLogStatus(RequestLogStatusChecker checker) throws Exception { final RequestLog log = requestLogQueue.take(); assertThat(log.availabilities()).contains(RequestLogAvailability.COMPLETE); final RpcRequest rpcReq = (RpcRequest) log.requestContent(); final RpcResponse rpcRes = (RpcResponse) log.responseContent(); assertThat(rpcReq).isNull(); assertThat((Object) rpcRes).isNotNull(); assertThat(rpcRes.cause()).isNotNull(); checker.check(((StatusException) rpcRes.cause()).getStatus()); }
/** * Wraps the given {@link Throwable} in a {@link StatusRuntimeException}. If it contains an * embedded {@link StatusException} or {@link StatusRuntimeException}, the returned exception will * contain the embedded trailers and status, with the given exception as the cause. Otherwise, an * exception will be generated from an {@link Status#UNKNOWN} status. */ private static StatusRuntimeException toStatusRuntimeException(Throwable t) { Throwable cause = checkNotNull(t, "t"); while (cause != null) { // If we have an embedded status, use it and replace the cause if (cause instanceof StatusException) { StatusException se = (StatusException) cause; return new StatusRuntimeException(se.getStatus(), se.getTrailers()); } else if (cause instanceof StatusRuntimeException) { StatusRuntimeException se = (StatusRuntimeException) cause; return new StatusRuntimeException(se.getStatus(), se.getTrailers()); } cause = cause.getCause(); } return Status.UNKNOWN.withDescription("unexpected exception").withCause(t) .asRuntimeException(); }
if (!subscription.isEmpty() && !subscription.equals(request.getSubscription())) { responseObserver.onError( new StatusException( Status.fromCode(Code.ABORTED) .withDescription("Can only set one subscription."))); if (request.getStreamAckDeadlineSeconds() == 0) { responseObserver.onError( new StatusException( Status.fromCode(Code.INVALID_ARGUMENT) .withDescription("A stream must be initialized with a ack deadline."))); closeStream(stream); responseObserver.onError( new StatusException( Status.fromCode(Code.ABORTED) .withDescription( closeStream(stream); responseObserver.onError( new StatusException( Status.fromCode(Code.ABORTED) .withDescription("Invalid modify ack deadline request.")));
private void checkRequestLog(RequestLogChecker checker) throws Exception { final RequestLog log = requestLogQueue.take(); assertThat(log.availabilities()).contains(RequestLogAvailability.COMPLETE); final RpcRequest rpcReq = (RpcRequest) log.requestContent(); final RpcResponse rpcRes = (RpcResponse) log.responseContent(); assertThat(rpcReq).isNotNull(); assertThat((Object) rpcRes).isNotNull(); assertThat(rpcReq.serviceType()).isEqualTo(GrpcLogUtil.class); final Status grpcStatus; if (rpcRes.cause() != null) { grpcStatus = ((StatusException) rpcRes.cause()).getStatus(); } else { grpcStatus = null; } checker.check(rpcReq, rpcRes, grpcStatus); }
@Test public void testFailedChannel_recoverableError_channelReopened() throws Exception { int expectedChannelCount = 1; Subscriber subscriber = startSubscriber( getTestSubscriberBuilder(testReceiver) .setSystemExecutorProvider( InstantiatingExecutorProvider.newBuilder().setExecutorThreadCount(1).build())); // Recoverable error fakeSubscriberServiceImpl.sendError(new StatusException(Status.INTERNAL)); assertEquals(1, fakeSubscriberServiceImpl.waitForClosedStreams(1)); assertEquals( expectedChannelCount, fakeSubscriberServiceImpl.waitForOpenedStreams(expectedChannelCount)); subscriber.stopAsync().awaitTerminated(); }
private static void checkRequestLog(RequestLogChecker checker) throws Exception { final RequestLog log = requestLogQueue.take(); assertThat(log.availabilities()).contains(RequestLogAvailability.COMPLETE); final RpcRequest rpcReq = (RpcRequest) log.requestContent(); final RpcResponse rpcRes = (RpcResponse) log.responseContent(); assertThat(rpcReq).isNotNull(); assertThat((Object) rpcRes).isNotNull(); assertThat(rpcReq.serviceType()).isEqualTo(GrpcLogUtil.class); final Status grpcStatus; if (rpcRes.cause() != null) { grpcStatus = ((StatusException) rpcRes.cause()).getStatus(); } else { grpcStatus = null; } checker.check(rpcReq, rpcRes, grpcStatus); }
@Test(expected = ExecutionException.class) public void testPublishFailureRetries_nonRetryableFailsImmediately() throws Exception { Publisher publisher = getTestPublisherBuilder() .setExecutorProvider(SINGLE_THREAD_EXECUTOR) .setRetrySettings( Publisher.Builder.DEFAULT_RETRY_SETTINGS .toBuilder() .setTotalTimeout(Duration.ofSeconds(10)) .build()) .setBatchingSettings( Publisher.Builder.DEFAULT_BATCHING_SETTINGS .toBuilder() .setElementCountThreshold(1L) .setDelayThreshold(Duration.ofSeconds(5)) .build()) .build(); // To demonstrate that reaching duration will trigger publish testPublisherServiceImpl.addPublishError(new StatusException(Status.INVALID_ARGUMENT)); ApiFuture<String> publishFuture1 = sendTestMessage(publisher, "A"); try { publishFuture1.get(); } finally { assertTrue(testPublisherServiceImpl.getCapturedRequests().size() >= 1); publisher.shutdown(); publisher.awaitTermination(1, TimeUnit.MINUTES); } }
@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); }