下面列出了怎么用io.grpc.StatusRuntimeException的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@SuppressWarnings("all")
public void dismissRecommendationExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockRecommendationService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<DismissRecommendationRequest.DismissRecommendationOperation> operations =
new ArrayList<>();
client.dismissRecommendation(customerId, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Override
public void getAvroSchema(
MetaStoreP.GetAvroSchemaRequest request,
StreamObserver<MetaStoreP.GetAvroSchemaResponse> responseObserver) {
try {
AbstractRegistry registry = metaStore.registries.get(request.getRegistryName());
ProtoDomain pContainer = registry.get();
String avroSchema = ProtoToAvroSchema.convert(pContainer, request.getMessageName());
responseObserver.onNext(
MetaStoreP.GetAvroSchemaResponse.newBuilder().setSchema(avroSchema).build());
responseObserver.onCompleted();
} catch (StatusException | IOException | StatusRuntimeException e) {
responseObserver.onError(e);
}
}
@Test
@SuppressWarnings("all")
public void mutateLabelsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockLabelService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<LabelOperation> operations = new ArrayList<>();
client.mutateLabels(customerId, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
public void killFrame(String host, String frameId, String message) {
RqdStaticKillRunningFrameRequest request =
RqdStaticKillRunningFrameRequest.newBuilder()
.setFrameId(frameId)
.setMessage(message)
.build();
if (testMode) {
return;
}
try {
logger.info("killing frame on " + host + ", source: " + message);
getStub(host).killRunningFrame(request);
} catch(StatusRuntimeException | ExecutionException e) {
throw new RqdClientException("failed to kill frame " + frameId, e);
}
}
@Test
@SuppressWarnings("all")
public void mutateBillingSetupExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockBillingSetupService.addException(exception);
try {
String customerId = "customerId-1772061412";
BillingSetupOperation operation = BillingSetupOperation.newBuilder().build();
client.mutateBillingSetup(customerId, operation);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void getDisplayKeywordViewExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockDisplayKeywordViewService.addException(exception);
try {
String formattedResourceName =
DisplayKeywordViewServiceClient.formatDisplayKeywordViewName(
"[CUSTOMER]", "[DISPLAY_KEYWORD_VIEW]");
client.getDisplayKeywordView(formattedResourceName);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void getFeedItemExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockFeedItemService.addException(exception);
try {
String formattedResourceName =
FeedItemServiceClient.formatFeedItemName("[CUSTOMER]", "[FEED_ITEM]");
client.getFeedItem(formattedResourceName);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void mutateCustomerExtensionSettingsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCustomerExtensionSettingService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<CustomerExtensionSettingOperation> operations = new ArrayList<>();
boolean partialFailure = true;
boolean validateOnly = false;
client.mutateCustomerExtensionSettings(customerId, operations, partialFailure, validateOnly);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
public synchronized String createTemporaryTable(Schema schema) {
CreateTemporaryTableRequest.Builder builder = CreateTemporaryTableRequest.newBuilder();
TableSchema.Builder schemaBuilder = TableSchema.newBuilder();
schema.build(schemaBuilder);
builder.setSchema(schemaBuilder.build());
CreateTemporaryTableRequest request = builder.build();
CreateTemporaryTableResponse response;
try {
response = _blockingStub.createTemporaryTable(request);
} catch (StatusRuntimeException e) {
e.printStackTrace();
throw e;
}
return response.getName();
}
@Test
@SuppressWarnings("all")
public void mutateCampaignExtensionSettingsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCampaignExtensionSettingService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<CampaignExtensionSettingOperation> operations = new ArrayList<>();
client.mutateCampaignExtensionSettings(customerId, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void promoteCampaignDraftExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCampaignDraftService.addException(exception);
try {
String formattedCampaignDraft =
CampaignDraftServiceClient.formatCampaignDraftName("[CUSTOMER]", "[CAMPAIGN_DRAFT]");
client.promoteCampaignDraftAsync(formattedCampaignDraft).get();
Assert.fail("No exception raised");
} catch (ExecutionException e) {
Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass());
InvalidArgumentException apiException = (InvalidArgumentException) e.getCause();
Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode());
}
}
@Test
@SuppressWarnings("all")
public void mutateSharedSetsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockSharedSetService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<SharedSetOperation> operations = new ArrayList<>();
client.mutateSharedSets(customerId, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void getLandingPageViewExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockLandingPageViewService.addException(exception);
try {
String formattedResourceName =
LandingPageViewServiceClient.formatLandingPageViewName(
"[CUSTOMER]", "[LANDING_PAGE_VIEW]");
client.getLandingPageView(formattedResourceName);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
/**
* Remove machine user
*
* @param requestId id of the request
* @param userCrn actor identifier
* @param machineUserName machine user to remove
*/
public void deleteMachineUser(String requestId, String userCrn, String machineUserName) {
checkNotNull(requestId);
checkNotNull(userCrn);
checkNotNull(machineUserName);
try {
newStub(requestId).deleteMachineUser(
UserManagementProto.DeleteMachineUserRequest.newBuilder()
.setAccountId(Crn.fromString(userCrn).getAccountId())
.setMachineUserNameOrCrn(machineUserName)
.build());
} catch (StatusRuntimeException e) {
if (e.getStatus().getCode().equals(
Status.NOT_FOUND.getCode())) {
LOGGER.info("Machine user not found.");
} else {
throw e;
}
}
}
@Test
@SuppressWarnings("all")
public void getExtensionFeedItemExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockExtensionFeedItemService.addException(exception);
try {
String formattedResourceName =
ExtensionFeedItemServiceClient.formatExtensionFeedItemName(
"[CUSTOMER]", "[EXTENSION_FEED_ITEM]");
client.getExtensionFeedItem(formattedResourceName);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void listCampaignDraftAsyncErrorsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCampaignDraftService.addException(exception);
try {
String formattedResourceName =
CampaignDraftServiceClient.formatCampaignDraftName("[CUSTOMER]", "[CAMPAIGN_DRAFT]");
client.listCampaignDraftAsyncErrors(formattedResourceName);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
private UserInfo getCurrentLoginUserInfo(boolean retry) {
try (AuthServiceChannel authServiceChannel = new AuthServiceChannel()) {
LOGGER.info(ModelDBMessages.AUTH_SERVICE_REQ_SENT_MSG);
UserInfo userInfo =
authServiceChannel.getUacServiceBlockingStub().getCurrentUser(Empty.newBuilder().build());
LOGGER.info(ModelDBMessages.AUTH_SERVICE_RES_RECEIVED_MSG);
if (userInfo == null || userInfo.getVertaInfo() == null) {
LOGGER.info("user not found {}", userInfo);
Status status =
Status.newBuilder()
.setCode(Code.NOT_FOUND_VALUE)
.setMessage("Current user could not be resolved.")
.build();
throw StatusProto.toStatusRuntimeException(status);
} else {
return userInfo;
}
} catch (StatusRuntimeException ex) {
return (UserInfo)
ModelDBUtils.retryOrThrowException(
ex, retry, (ModelDBUtils.RetryCallInterface<UserInfo>) this::getCurrentLoginUserInfo);
}
}
@Test
public void alleMatches() {
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().forAllExceptions();
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 mutateCustomerManagerLinkExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCustomerManagerLinkService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<CustomerManagerLinkOperation> operations = new ArrayList<>();
client.mutateCustomerManagerLink(customerId, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void getExpandedLandingPageViewExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockExpandedLandingPageViewService.addException(exception);
try {
String formattedResourceName =
ExpandedLandingPageViewServiceClient.formatExpandedLandingPageViewName(
"[CUSTOMER]", "[EXPANDED_LANDING_PAGE_VIEW]");
client.getExpandedLandingPageView(formattedResourceName);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void mutateAdGroupCriterionLabelsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockAdGroupCriterionLabelService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<AdGroupCriterionLabelOperation> operations = new ArrayList<>();
client.mutateAdGroupCriterionLabels(customerId, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
private void setRoleBindingOnAuthService(boolean retry, RoleBinding roleBinding) {
try (AuthServiceChannel authServiceChannel = new AuthServiceChannel()) {
LOGGER.info(ModelDBMessages.CALL_TO_ROLE_SERVICE_MSG);
SetRoleBinding.Response setRoleBindingResponse =
authServiceChannel
.getRoleServiceBlockingStub()
.setRoleBinding(SetRoleBinding.newBuilder().setRoleBinding(roleBinding).build());
LOGGER.info(ModelDBMessages.ROLE_SERVICE_RES_RECEIVED_MSG);
LOGGER.trace(ModelDBMessages.ROLE_SERVICE_RES_RECEIVED_TRACE_MSG, setRoleBindingResponse);
} catch (StatusRuntimeException ex) {
ModelDBUtils.retryOrThrowException(
ex,
retry,
(ModelDBUtils.RetryCallInterface<Void>)
(retry1) -> {
setRoleBindingOnAuthService(retry1, roleBinding);
return null;
});
}
}
@Test
@SuppressWarnings("all")
public void getGeographicViewExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockGeographicViewService.addException(exception);
try {
String formattedResourceName =
GeographicViewServiceClient.formatGeographicViewName("[CUSTOMER]", "[GEOGRAPHIC_VIEW]");
client.getGeographicView(formattedResourceName);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void mutateAdGroupBidModifiersExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockAdGroupBidModifierService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<AdGroupBidModifierOperation> operations = new ArrayList<>();
client.mutateAdGroupBidModifiers(customerId, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void mutateUserListsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockUserListService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<UserListOperation> operations = new ArrayList<>();
client.mutateUserLists(customerId, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
/** Returns a socket. */
@Override
public void getSocket(
GetSocketRequest request, StreamObserver<GetSocketResponse> responseObserver) {
InternalInstrumented<SocketStats> s = channelz.getSocket(request.getSocketId());
if (s == null) {
responseObserver.onError(
Status.NOT_FOUND.withDescription("Can't find socket " + request.getSocketId())
.asRuntimeException());
return;
}
GetSocketResponse resp;
try {
resp =
GetSocketResponse.newBuilder().setSocket(ChannelzProtoUtil.toSocket(s)).build();
} catch (StatusRuntimeException e) {
responseObserver.onError(e);
return;
}
responseObserver.onNext(resp);
responseObserver.onCompleted();
}
@Test
@SuppressWarnings("all")
public void createCustomerClientExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCustomerService.addException(exception);
try {
String customerId = "customerId-1772061412";
Customer customerClient = Customer.newBuilder().build();
StringValue emailAddress = StringValue.newBuilder().build();
AccessRoleEnum.AccessRole accessRole = AccessRoleEnum.AccessRole.UNSPECIFIED;
client.createCustomerClient(customerId, customerClient, emailAddress, accessRole);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void getGoogleAdsFieldExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockGoogleAdsFieldService.addException(exception);
try {
String formattedResourceName =
GoogleAdsFieldServiceClient.formatGoogleAdsFieldName("[GOOGLE_ADS_FIELD]");
client.getGoogleAdsField(formattedResourceName);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void mutateFeedItemsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockFeedItemService.addException(exception);
try {
String customerId = "customerId-1772061412";
List<FeedItemOperation> operations = new ArrayList<>();
client.mutateFeedItems(customerId, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
/**
* Test that when RPC cancellation propagates up a call chain, the cancellation of the parent
* RPC triggers cancellation of all of its children.
*/
@Test
public void testCascadingCancellationViaLeafFailure() throws Exception {
// All nodes (15) except one edge of the tree (4) will be cancelled.
observedCancellations = new CountDownLatch(11);
receivedCancellations = new CountDownLatch(11);
startCallTreeServer(3);
try {
// Use response size limit to control tree nodeCount.
blockingStub.unaryCall(Messages.SimpleRequest.newBuilder().setResponseSize(3).build());
fail("Expected abort");
} catch (StatusRuntimeException sre) {
// Wait for the workers to finish
Status status = sre.getStatus();
// Outermost caller observes ABORTED propagating up from the failing leaf,
// The descendant RPCs are cancelled so they receive CANCELLED.
assertEquals(Status.Code.ABORTED, status.getCode());
if (!observedCancellations.await(5, TimeUnit.SECONDS)) {
fail("Expected number of cancellations not observed by clients");
}
if (!receivedCancellations.await(5, TimeUnit.SECONDS)) {
fail("Expected number of cancellations to be received by servers not observed");
}
}
}