Java源码示例:com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo

示例1
@Before
public void setUp() throws Exception {
  accessDenied =
      googleJsonResponseException(
          HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Forbidden", "Forbidden");
  statusOk = googleJsonResponseException(HttpStatusCodes.STATUS_CODE_OK, "A reason", "ok");
  notFound =
      googleJsonResponseException(
          HttpStatusCodes.STATUS_CODE_NOT_FOUND, "Not found", "Not found");
  badRange =
      googleJsonResponseException(
          ApiErrorExtractor.STATUS_CODE_RANGE_NOT_SATISFIABLE, "Bad range", "Bad range");
  alreadyExists = googleJsonResponseException(409, "409", "409");
  resourceNotReady =
      googleJsonResponseException(
          400, ApiErrorExtractor.RESOURCE_NOT_READY_REASON, "Resource not ready");

  // This works because googleJsonResponseException takes final ErrorInfo
  ErrorInfo errorInfo = new ErrorInfo();
  errorInfo.setReason(ApiErrorExtractor.RATE_LIMITED_REASON);
  notRateLimited = googleJsonResponseException(POSSIBLE_RATE_LIMIT, errorInfo, "");
  errorInfo.setDomain(ApiErrorExtractor.USAGE_LIMITS_DOMAIN);
  rateLimited = googleJsonResponseException(POSSIBLE_RATE_LIMIT, errorInfo, "");
  errorInfo.setDomain(ApiErrorExtractor.GLOBAL_DOMAIN);
  bigqueryRateLimited = googleJsonResponseException(POSSIBLE_RATE_LIMIT, errorInfo, "");
}
 
示例2
protected static void checkGoogleJsonResponseException(GoogleJsonResponseException e)
    throws GoogleJsonResponseException {
  GoogleJsonError err = e.getDetails();
  // err can be null if response is not JSON
  if (err != null) {
    // For errors in the 4xx range, print out the errors and continue normally.
    if (err.getCode() >= 400 && err.getCode() < 500) {
      System.out.printf("There are %d error(s)%n", err.getErrors().size());
      for (ErrorInfo info : err.getErrors()) {
        System.out.printf("- [%s] %s%n", info.getReason(), info.getMessage());
      }
    } else {
      throw e;
    }
  } else {
    throw e;
  }
}
 
示例3
/**
 * Create an error result when invalid parameters are detected during {@link
 * TestingHttpRequest#execute()}.
 *
 * @param method problem method ("GET", "PUT", etc.).
 * @param location problem url.
 * @param message error string.
 * @return an error result.
 */
private GoogleJsonError badRequest(String method, String location, String message, int code) {
  return new GoogleJsonError()
      .set("code", code)
      .set("message", "Bad Request: " + method)
      .set(
          "errors",
          Collections.singletonList(
              new ErrorInfo().set("location", location).set("message", message)));
}
 
示例4
private static GoogleJsonResponseException fakeGoogleJsonResponseException(
    int httpStatus, String reason, String message) throws IOException {
  ErrorInfo errorInfo = new ErrorInfo();
  errorInfo.setReason(reason);
  errorInfo.setMessage(message);
  return fakeGoogleJsonResponseException(httpStatus, errorInfo, message);
}
 
示例5
private static GoogleJsonResponseException fakeGoogleJsonResponseException(
    int status, ErrorInfo errorInfo, String message) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          errorInfo.setFactory(jsonFactory);
          GoogleJsonError jsonError = new GoogleJsonError();
          jsonError.setCode(status);
          jsonError.setErrors(Collections.singletonList(errorInfo));
          jsonError.setMessage(message);
          jsonError.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", jsonError);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
示例6
/** Builds a fake GoogleJsonResponseException for testing API error handling. */
private static GoogleJsonResponseException googleJsonResponseException(
    final int status, final String reason, final String message) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          ErrorInfo errorInfo = new ErrorInfo();
          errorInfo.setReason(reason);
          errorInfo.setMessage(message);
          errorInfo.setFactory(jsonFactory);
          GenericJson error = new GenericJson();
          error.set("code", status);
          error.set("errors", Arrays.asList(errorInfo));
          error.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", error);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
示例7
/** A helper that generates the error JSON payload that Google APIs produce. */
private static GoogleJsonErrorContainer errorWithReasonAndStatus(String reason, int status) {
  ErrorInfo info = new ErrorInfo();
  info.setReason(reason);
  info.setDomain("global");
  // GoogleJsonError contains one or more ErrorInfo objects; our utiities read the first one.
  GoogleJsonError error = new GoogleJsonError();
  error.setErrors(ImmutableList.of(info));
  error.setCode(status);
  error.setMessage(reason);
  // The actual JSON response is an error container.
  GoogleJsonErrorContainer container = new GoogleJsonErrorContainer();
  container.setError(error);
  return container;
}
 
示例8
/** Builds a fake GoogleJsonResponseException for testing API error handling. */
private static GoogleJsonResponseException googleJsonResponseException(
    final int status, final String reason, final String message) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          ErrorInfo errorInfo = new ErrorInfo();
          errorInfo.setReason(reason);
          errorInfo.setMessage(message);
          errorInfo.setFactory(jsonFactory);
          GenericJson error = new GenericJson();
          error.set("code", status);
          error.set("errors", Arrays.asList(errorInfo));
          error.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", error);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
示例9
/**
 * Determines if a given Throwable is caused by a rate limit being applied. Recursively checks
 * getCause() if outer exception isn't an instance of the correct class.
 *
 * @param e The Throwable to check.
 * @return True if the Throwable is a result of rate limiting being applied.
 */
public boolean rateLimited(IOException e) {
  ErrorInfo errorInfo = getErrorInfo(e);
  if (errorInfo != null) {
    String domain = errorInfo.getDomain();
    boolean isRateLimitedOrGlobalDomain =
        USAGE_LIMITS_DOMAIN.equals(domain) || GLOBAL_DOMAIN.equals(domain);
    String reason = errorInfo.getReason();
    boolean isRateLimitedReason =
        RATE_LIMITED_REASON.equals(reason) || USER_RATE_LIMITED_REASON.equals(reason);
    return isRateLimitedOrGlobalDomain && isRateLimitedReason;
  }
  return false;
}
 
示例10
/**
 * Get the first ErrorInfo from an IOException if it is an instance of
 * GoogleJsonResponseException, otherwise return null.
 */
@Nullable
protected ErrorInfo getErrorInfo(IOException e) {
  GoogleJsonError jsonError = getJsonError(e);
  List<ErrorInfo> errors = jsonError != null ? jsonError.getErrors() : ImmutableList.of();
  return errors != null ? Iterables.getFirst(errors, null) : null;
}
 
示例11
/** Builds a fake GoogleJsonResponseException for testing API error handling. */
private static GoogleJsonResponseException googleJsonResponseException(
    int httpStatus, String reason, String message, String httpStatusString) throws IOException {
  ErrorInfo errorInfo = new ErrorInfo();
  errorInfo.setReason(reason);
  errorInfo.setMessage(message);
  return googleJsonResponseException(httpStatus, errorInfo, httpStatusString);
}
 
示例12
private static GoogleJsonResponseException googleJsonResponseException(
    int status, ErrorInfo errorInfo, String httpStatusString) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          errorInfo.setFactory(jsonFactory);
          GoogleJsonError jsonError = new GoogleJsonError();
          jsonError.setCode(status);
          jsonError.setErrors(Collections.singletonList(errorInfo));
          jsonError.setMessage(httpStatusString);
          jsonError.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", jsonError);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
示例13
@Override
public void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders) {
  failureCalls++;
  GoogleJsonError error = e.getError();
  ErrorInfo errorInfo = error.getErrors().get(0);
  assertEquals(ERROR_DOMAIN, errorInfo.getDomain());
  assertEquals(ERROR_REASON, errorInfo.getReason());
  assertEquals(ERROR_MSG, errorInfo.getMessage());
  assertEquals(ERROR_CODE, error.getCode());
  assertEquals(ERROR_MSG, error.getMessage());
}
 
示例14
@Override
public void onFailure(ErrorOutput.ErrorBody e, HttpHeaders responseHeaders) throws IOException {
  GoogleJsonErrorContainer errorContainer = new GoogleJsonErrorContainer();

  if (e.hasError()) {
    ErrorOutput.ErrorProto errorProto = e.getError();

    GoogleJsonError error = new GoogleJsonError();
    if (errorProto.hasCode()) {
      error.setCode(errorProto.getCode());
    }
    if (errorProto.hasMessage()) {
      error.setMessage(errorProto.getMessage());
    }

    List<ErrorInfo> errorInfos = new ArrayList<ErrorInfo>(errorProto.getErrorsCount());
    for (ErrorOutput.IndividualError individualError : errorProto.getErrorsList()) {
      ErrorInfo errorInfo = new ErrorInfo();
      if (individualError.hasDomain()) {
        errorInfo.setDomain(individualError.getDomain());
      }
      if (individualError.hasMessage()) {
        errorInfo.setMessage(individualError.getMessage());
      }
      if (individualError.hasReason()) {
        errorInfo.setReason(individualError.getReason());
      }
      errorInfos.add(errorInfo);
    }
    error.setErrors(errorInfos);
    errorContainer.setError(error);
  }
  callback.onFailure(errorContainer, responseHeaders);
}
 
示例15
/**
 * Determines if the exception is a non-recoverable access denied code (such as account closed or
 * marked for deletion).
 */
public boolean accessDeniedNonRecoverable(IOException e) {
  ErrorInfo errorInfo = getErrorInfo(e);
  String reason = errorInfo != null ? errorInfo.getReason() : null;
  return ACCOUNT_DISABLED_REASON.equals(reason) || ACCESS_NOT_CONFIGURED_REASON.equals(reason);
}
 
示例16
/**
 * Determines if the given exception indicates 'field size too large'. Recursively checks
 * getCause() if outer exception isn't an instance of the correct class.
 */
public boolean fieldSizeTooLarge(IOException e) {
  ErrorInfo errorInfo = getErrorInfo(e);
  return errorInfo != null && FIELD_SIZE_TOO_LARGE_REASON.equals(errorInfo.getReason());
}
 
示例17
/**
 * Determines if the given exception indicates 'resource not ready'. Recursively checks getCause()
 * if outer exception isn't an instance of the correct class.
 */
public boolean resourceNotReady(IOException e) {
  ErrorInfo errorInfo = getErrorInfo(e);
  return errorInfo != null && RESOURCE_NOT_READY_REASON.equals(errorInfo.getReason());
}
 
示例18
@Nullable
public String getDebugInfo(IOException e) {
  ErrorInfo errorInfo = getErrorInfo(e);
  return errorInfo != null ? (String) errorInfo.getUnknownKeys().get(DEBUG_INFO_FIELD) : null;
}