下面列出了怎么用io.grpc.Status的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onReady() {
class StreamOnReady extends ContextRunnable {
StreamOnReady() {
super(context);
}
@Override
public final void runInContext() {
try {
observer.onReady();
} catch (Throwable t) {
Status status =
Status.CANCELLED.withCause(t).withDescription("Failed to call onReady.");
stream.cancel(status);
close(status, new Metadata());
}
}
}
callExecutor.execute(new StreamOnReady());
}
@Test
@SuppressWarnings("all")
public void mutateBiddingStrategiesExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockBiddingStrategyService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<BiddingStrategyOperation> operations = new ArrayList<>();
boolean partialFailure = true;
boolean validateOnly = false;
client.mutateBiddingStrategies(customerId, operations, partialFailure, validateOnly);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void mutateAccountBudgetProposalExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockAccountBudgetProposalService.addException(exception);
try {
String customerId = "customerId-1772061412";
AccountBudgetProposalOperation operation =
AccountBudgetProposalOperation.newBuilder().build();
boolean validateOnly = false;
client.mutateAccountBudgetProposal(customerId, operation, validateOnly);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Override
public void onNext(WriteRequest request) {
checkState(
(hasSeenResourceName && request.getResourceName().isEmpty())
|| request.getResourceName().equals(resourceName));
hasSeenResourceName = true;
checkState(!finished);
ByteString data = request.getData();
if (data.isEmpty() || request.getWriteOffset() == out.size()) {
try {
request.getData().writeTo(out);
finished = request.getFinishWrite();
if (finished) {
long committedSize = out.size();
content.set(out.toByteString());
responseObserver.onNext(
WriteResponse.newBuilder().setCommittedSize(committedSize).build());
}
} catch (IOException e) {
responseObserver.onError(Status.fromThrowable(e).asException());
}
} else {
responseObserver.onError(Status.INVALID_ARGUMENT.asException());
}
}
@Test
@SuppressWarnings("all")
public void getMutateJobExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockMutateJobService.addException(exception);
try {
String formattedResourceName =
MutateJobServiceClient.formatMutateJobName("[CUSTOMER]", "[MUTATE_JOB]");
client.getMutateJob(formattedResourceName);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
private InputStream getCompressedBody() {
if (decompressor == Codec.Identity.NONE) {
throw Status.INTERNAL.withDescription(
"Can't decode compressed gRPC message as compression not configured")
.asRuntimeException();
}
try {
// Enforce the maxMessageSize limit on the returned stream.
InputStream unlimitedStream =
decompressor.decompress(ReadableBuffers.openStream(nextFrame, true));
return new SizeEnforcingInputStream(
unlimitedStream, maxInboundMessageSize, statsTraceCtx);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
@SuppressWarnings("all")
public void mutateExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockGoogleAdsService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<MutateOperation> mutateOperations = new ArrayList<>();
boolean partialFailure = true;
boolean validateOnly = false;
client.mutate(customerId, mutateOperations, partialFailure, validateOnly);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void mutateAdGroupLabelsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockAdGroupLabelService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<AdGroupLabelOperation> operations = new ArrayList<>();
client.mutateAdGroupLabels(customerId, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void mutateBiddingStrategiesExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockBiddingStrategyService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<BiddingStrategyOperation> operations = new ArrayList<>();
boolean partialFailure = true;
boolean validateOnly = false;
client.mutateBiddingStrategies(customerId, operations, partialFailure, validateOnly);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
public void exactTypeMatches() {
GreeterGrpc.GreeterImplBase svc = new GreeterGrpc.GreeterImplBase() {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
responseObserver.onError(new ArithmeticException("Divide by zero"));
}
};
ServerInterceptor interceptor = new TransmitUnexpectedExceptionInterceptor().forExactType(ArithmeticException.class);
serverRule.getServiceRegistry().addService(ServerInterceptors.intercept(svc, interceptor));
GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverRule.getChannel());
assertThatThrownBy(() -> stub.sayHello(HelloRequest.newBuilder().setName("World").build()))
.isInstanceOf(StatusRuntimeException.class)
.matches(sre -> ((StatusRuntimeException) sre).getStatus().getCode().equals(Status.INTERNAL.getCode()), "is Status.INTERNAL")
.hasMessageContaining("Divide by zero");
}
@Test
@SuppressWarnings("all")
public void mutateCustomInterestsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCustomInterestService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<CustomInterestOperation> operations = new ArrayList<>();
client.mutateCustomInterests(customerId, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void mutateCampaignLabelsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCampaignLabelService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<CampaignLabelOperation> operations = new ArrayList<>();
client.mutateCampaignLabels(customerId, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Override
public void exitServerListenerMethod(@Nullable Throwable thrown,
ServerCall.Listener<?> listener,
@Nullable Transaction transaction,
boolean isLastMethod) {
if (transaction == null) {
return;
}
transaction.deactivate();
if (isLastMethod || null != thrown) {
// when there is a runtime exception thrown in one of the listener methods the calling code will catch it
// and set 'unknown' status, we just replicate this behavior as we don't instrument the part that does this
if (thrown != null) {
setTransactionStatus(Status.UNKNOWN, thrown, transaction);
}
transaction.end();
serverListenerTransactions.remove(listener);
}
}
@Test
public void maxHeaderListSizeShouldBeEnforcedOnClient() throws Exception {
startServer();
NettyClientTransport transport =
newTransport(newNegotiator(), DEFAULT_MAX_MESSAGE_SIZE, 1, null, true);
callMeMaybe(transport.start(clientTransportListener));
try {
// Send a single RPC and wait for the response.
new Rpc(transport, new Metadata()).halfClose().waitForResponse();
fail("The stream should have been failed due to client received header exceeds header list"
+ " size limit!");
} catch (Exception e) {
Throwable rootCause = getRootCause(e);
Status status = ((StatusException) rootCause).getStatus();
assertEquals(Status.Code.INTERNAL, status.getCode());
assertEquals("HTTP/2 error code: PROTOCOL_ERROR\nReceived Rst Stream",
status.getDescription());
}
}
public Book createBook(long shelfId, Book book) throws StatusException {
synchronized (lock) {
@Nullable ShelfInfo shelfInfo = shelves.get(shelfId);
if (shelfInfo == null) {
throw Status.NOT_FOUND
.withDescription("Unknown shelf ID")
.asException();
}
shelfInfo.lastBookId++;
book = book.toBuilder()
.setId(shelfInfo.lastBookId)
.build();
shelfInfo.books.put(shelfInfo.lastBookId, book);
}
return book;
}
BackoffCacheEntry(RouteLookupRequest request, Status status, BackoffPolicy backoffPolicy) {
super(request);
this.status = checkNotNull(status, "status");
this.backoffPolicy = checkNotNull(backoffPolicy, "backoffPolicy");
long delayNanos = backoffPolicy.nextBackoffNanos();
this.expireNanos = timeProvider.currentTimeNanos() + delayNanos;
this.scheduledHandle =
synchronizationContext.schedule(
new Runnable() {
@Override
public void run() {
transitionToPending();
}
},
delayNanos,
TimeUnit.NANOSECONDS,
scheduledExecutorService);
}
@Test
@SuppressWarnings("all")
public void mutateCampaignDraftsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCampaignDraftService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<CampaignDraftOperation> operations = new ArrayList<>();
client.mutateCampaignDrafts(customerId, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
public void blockingServerStreamingCall_HasBlockingStubType() {
NoopClientCall<Integer, Integer> call = new NoopClientCall<Integer, Integer>() {
@Override
public void start(io.grpc.ClientCall.Listener<Integer> listener, Metadata headers) {
listener.onMessage(1);
listener.onClose(Status.OK, new Metadata());
}
};
when(mockChannel.newCall(
ArgumentMatchers.<MethodDescriptor<Integer, Integer>>any(), any(CallOptions.class)))
.thenReturn(call);
Iterator<Integer> unused =
ClientCalls.blockingServerStreamingCall(mockChannel, UNARY_METHOD, CallOptions.DEFAULT, 1);
verify(mockChannel).newCall(methodDescriptorCaptor.capture(), callOptionsCaptor.capture());
CallOptions capturedCallOption = callOptionsCaptor.getValue();
assertThat(capturedCallOption.getOption(ClientCalls.STUB_TYPE_OPTION))
.isEquivalentAccordingToCompareTo(StubType.BLOCKING);
}
@Test
public void fail_inline() {
final Status error = Status.FAILED_PRECONDITION.withDescription("channel not secure for creds");
when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
CallCredentials.MetadataApplier applier =
(CallCredentials.MetadataApplier) invocation.getArguments()[2];
applier.fail(error);
return null;
}
}).when(mockCreds).applyRequestMetadata(any(RequestInfo.class),
same(mockExecutor), any(CallCredentials.MetadataApplier.class));
FailingClientStream stream =
(FailingClientStream) transport.newStream(method, origHeaders, callOptions);
verify(mockTransport, never()).newStream(method, origHeaders, callOptions);
assertSame(error, stream.getError());
}
@Test
@SuppressWarnings("all")
public void uploadClickConversionsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockConversionUploadService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<ClickConversion> conversions = new ArrayList<>();
client.uploadClickConversions(customerId, conversions);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
protected void errorOperation(
Operation operation, RequestMetadata requestMetadata, com.google.rpc.Status status)
throws InterruptedException {
if (operation.getDone()) {
throw new IllegalStateException("Trying to error already completed operation [" + name + "]");
}
ExecuteOperationMetadata metadata = expectExecuteOperationMetadata(operation);
if (metadata == null) {
metadata = ExecuteOperationMetadata.getDefaultInstance();
}
CompletedOperationMetadata completedMetadata =
CompletedOperationMetadata.newBuilder()
.setExecuteOperationMetadata(
metadata.toBuilder().setStage(ExecutionStage.Value.COMPLETED).build())
.setRequestMetadata(requestMetadata)
.build();
putOperation(
operation
.toBuilder()
.setDone(true)
.setMetadata(Any.pack(completedMetadata))
.setResponse(Any.pack(ExecuteResponse.newBuilder().setStatus(status).build()))
.build());
}
@Test
@SuppressWarnings("all")
public void mutateAccountBudgetProposalExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockAccountBudgetProposalService.addException(exception);
try {
String customerId = "customerId-1772061412";
AccountBudgetProposalOperation operation =
AccountBudgetProposalOperation.newBuilder().build();
client.mutateAccountBudgetProposal(customerId, operation);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
public void receiveDataWithoutHeader() throws Exception {
initTransport();
MockStreamListener listener = new MockStreamListener();
OkHttpClientStream stream =
clientTransport.newStream(method, new Metadata(), CallOptions.DEFAULT);
stream.start(listener);
stream.request(1);
Buffer buffer = createMessageFrame(new byte[1]);
frameHandler().data(false, 3, buffer, (int) buffer.size());
// Trigger the failure by a trailer.
frameHandler().headers(
true, true, 3, 0, grpcResponseHeaders(), HeadersMode.HTTP_20_HEADERS);
listener.waitUntilStreamClosed();
assertEquals(Status.INTERNAL.getCode(), listener.status.getCode());
assertTrue(listener.status.getDescription().startsWith("headers not received before payload"));
assertEquals(0, listener.messages.size());
shutdownAndVerify();
}
@Test
@SuppressWarnings("all")
public void getTopicViewExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockTopicViewService.addException(exception);
try {
String formattedResourceName =
TopicViewServiceClient.formatTopicViewName("[CUSTOMER]", "[TOPIC_VIEW]");
client.getTopicView(formattedResourceName);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Override
public void handleNameResolutionError(final Status error) {
class ErrorPicker extends SubchannelPicker {
@Override
public PickResult pickSubchannel(PickSubchannelArgs args) {
return PickResult.withError(error);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("error", error)
.toString();
}
}
if (routeLookupClient != null) {
routeLookupClient.close();
routeLookupClient = null;
lbPolicyConfiguration = null;
}
helper.updateBalancingState(ConnectivityState.TRANSIENT_FAILURE, new ErrorPicker());
}
@Test
@SuppressWarnings("all")
public void getLabelExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockLabelService.addException(exception);
try {
String formattedResourceName = LabelServiceClient.formatLabelName("[CUSTOMER]", "[LABEL]");
client.getLabel(formattedResourceName);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
private void shouldHeadersBeFlushed(boolean shouldBeFlushed) throws Exception {
initTransport();
MockStreamListener listener = new MockStreamListener();
OkHttpClientStream stream =
clientTransport.newStream(method, new Metadata(), CallOptions.DEFAULT);
stream.start(listener);
verify(frameWriter, timeout(TIME_OUT_MS)).synStream(
eq(false), eq(false), eq(3), eq(0), ArgumentMatchers.<Header>anyList());
if (shouldBeFlushed) {
verify(frameWriter, timeout(TIME_OUT_MS)).flush();
} else {
verify(frameWriter, timeout(TIME_OUT_MS).times(0)).flush();
}
stream.cancel(Status.CANCELLED);
}
@Test
public void cancelWhileBufferedShouldSucceed() throws Exception {
// Force the stream to be buffered.
receiveMaxConcurrentStreams(0);
ChannelFuture createFuture = createStream();
assertFalse(createFuture.isDone());
ChannelFuture cancelFuture = cancelStream(Status.CANCELLED);
assertTrue(cancelFuture.isSuccess());
assertTrue(createFuture.isDone());
assertTrue(createFuture.isSuccess());
}
@Test
public void hedging_perRpcBufferLimitExceeded() {
ClientStream mockStream1 = mock(ClientStream.class);
ClientStream mockStream2 = mock(ClientStream.class);
doReturn(mockStream1).when(retriableStreamRecorder).newSubstream(0);
doReturn(mockStream2).when(retriableStreamRecorder).newSubstream(1);
hedgingStream.start(masterListener);
ArgumentCaptor<ClientStreamListener> sublistenerCaptor1 =
ArgumentCaptor.forClass(ClientStreamListener.class);
verify(mockStream1).start(sublistenerCaptor1.capture());
ClientStreamTracer bufferSizeTracer1 = bufferSizeTracer;
bufferSizeTracer1.outboundWireSize(PER_RPC_BUFFER_LIMIT - 1);
fakeClock.forwardTime(HEDGING_DELAY_IN_SECONDS, TimeUnit.SECONDS);
ArgumentCaptor<ClientStreamListener> sublistenerCaptor2 =
ArgumentCaptor.forClass(ClientStreamListener.class);
verify(mockStream2).start(sublistenerCaptor2.capture());
ClientStreamTracer bufferSizeTracer2 = bufferSizeTracer;
bufferSizeTracer2.outboundWireSize(PER_RPC_BUFFER_LIMIT - 1);
verify(retriableStreamRecorder, never()).postCommit();
// bufferLimitExceeded
bufferSizeTracer2.outboundWireSize(2);
ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class);
verify(mockStream1).cancel(statusCaptor.capture());
assertEquals(Status.CANCELLED.getCode(), statusCaptor.getValue().getCode());
assertEquals(CANCELLED_BECAUSE_COMMITTED, statusCaptor.getValue().getDescription());
verify(retriableStreamRecorder).postCommit();
verifyNoMoreInteractions(mockStream1);
verifyNoMoreInteractions(mockStream2);
}
FakeNameResolverFactory(
List<URI> expectedUris,
List<EquivalentAddressGroup> servers,
boolean resolvedAtStart,
Status error) {
this.expectedUris = expectedUris;
this.servers = servers;
this.resolvedAtStart = resolvedAtStart;
this.error = error;
}