com.amazonaws.AmazonServiceException类的使用及代码示例

x33g5p2x  于2022-01-15 转载在 其他  
字(14.6k)|赞(0)|评价(0)|浏览(414)

本文整理了Java中com.amazonaws.AmazonServiceException类的一些代码示例,展示了AmazonServiceException类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。AmazonServiceException类的具体详情如下:
包路径:com.amazonaws.AmazonServiceException
类名称:AmazonServiceException

AmazonServiceException介绍

[英]Extension of SdkClientException that represents an error response returned by an Amazon web service. Receiving an exception of this type indicates that the caller's request was correctly transmitted to the service, but for some reason, the service was not able to process it, and returned an error response instead.

AmazonServiceException provides callers several pieces of information that can be used to obtain more information about the error and why it occurred. In particular, the errorType field can be used to determine if the caller's request was invalid, or the service encountered an error on the server side while processing it.
[中]SdkClientException的扩展,表示Amazon web服务返回的错误响应。接收到此类型的异常表示调用方的请求已正确传输到服务,但由于某种原因,服务无法处理该请求,而是返回了错误响应。
AmazonServiceException为调用者提供了一些信息,可用于获取有关错误及其发生原因的更多信息。特别是,errorType字段可用于确定调用方的请求是否无效,或者服务在处理请求时在服务器端遇到错误。

代码示例

代码示例来源:origin: awsdocs/aws-doc-sdk-examples

public static void main(String[] args) {

    AmazonGuardDuty guardduty =
      AmazonGuardDutyClientBuilder.defaultClient();

    try {
      ListDetectorsRequest request = new ListDetectorsRequest();

      ListDetectorsResult response = guardduty.listDetectors(request);

      for (String detectorId : response.getDetectorIds())
      {
        System.out.println("DetectorId: " + detectorId );
      }
    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

  }
}

代码示例来源:origin: aws/aws-sdk-java

private AmazonServiceException handleAse(HttpResponse response) throws Exception {
  final int statusCode = response.getStatusCode();
  try {
    return delegate.handle(response);
  } catch(InterruptedException e) {
    throw e;
  } catch (Exception e) {
    // If the errorResponseHandler doesn't work, then check for error responses that don't have any content
    if (statusCode == 413) {
      AmazonServiceException exception = new AmazonServiceException("Request entity too large");
      exception.setServiceName(response.getRequest().getServiceName());
      exception.setStatusCode(statusCode);
      exception.setErrorType(AmazonServiceException.ErrorType.Client);
      exception.setErrorCode("Request entity too large");
      return exception;
    } else if (statusCode >= 500 && statusCode < 600) {
      AmazonServiceException exception = new AmazonServiceException(response.getStatusText());
      exception.setServiceName(response.getRequest().getServiceName());
      exception.setStatusCode(statusCode);
      exception.setErrorType(AmazonServiceException.ErrorType.Service);
      exception.setErrorCode(response.getStatusText());
      return exception;
    } else {
      throw e;
    }
  }
}

代码示例来源:origin: apache/nifi

protected List<FlowFile> processServiceException(final ProcessSession session, List<FlowFile> flowFiles,
    AmazonServiceException exception) {
  List<FlowFile> failedFlowFiles = new ArrayList<>();
  for (FlowFile flowFile : flowFiles) {
    Map<String,String> attributes = new HashMap<>();
    attributes.put(DYNAMODB_ERROR_EXCEPTION_MESSAGE, exception.getMessage() );
    attributes.put(DYNAMODB_ERROR_CODE, exception.getErrorCode() );
    attributes.put(DYNAMODB_ERROR_MESSAGE, exception.getErrorMessage() );
    attributes.put(DYNAMODB_ERROR_TYPE, exception.getErrorType().name() );
    attributes.put(DYNAMODB_ERROR_SERVICE, exception.getServiceName() );
    attributes.put(DYNAMODB_ERROR_RETRYABLE, Boolean.toString(exception.isRetryable()));
    attributes.put(DYNAMODB_ERROR_REQUEST_ID, exception.getRequestId() );
    attributes.put(DYNAMODB_ERROR_STATUS_CODE, Integer.toString(exception.getStatusCode()) );
    attributes.put(DYNAMODB_ERROR_EXCEPTION_MESSAGE, exception.getMessage() );
    attributes.put(DYNAMODB_ERROR_RETRYABLE, Boolean.toString(exception.isRetryable()));
    flowFile = session.putAllAttributes(flowFile, attributes);
    failedFlowFiles.add(flowFile);
  }
  return failedFlowFiles;
}

代码示例来源:origin: aws/aws-sdk-java

@Override
public String getMessage() {
  return getErrorMessage()
    + " (Service: " + getServiceName()
    + "; Status Code: " + getStatusCode()
    + "; Error Code: " + getErrorCode()
    + "; Request ID: " + getRequestId() + ")";
}

代码示例来源:origin: apache/incubator-druid

static boolean isServiceExceptionRecoverable(AmazonServiceException ex)
{
 final boolean isIOException = ex.getCause() instanceof IOException;
 final boolean isTimeout = "RequestTimeout".equals(ex.getErrorCode());
 return isIOException || isTimeout;
}

代码示例来源:origin: aws/aws-sdk-java

@Override
public boolean doesBucketExistV2(String bucketName) throws SdkClientException {
  try {
    getBucketAcl(bucketName);
    return true;
  } catch (AmazonServiceException ase) {
    // A redirect error or an AccessDenied exception means the bucket exists but it's not in this region
    // or we don't have permissions to it.
    if ((ase.getStatusCode() == Constants.BUCKET_REDIRECT_STATUS_CODE) || "AccessDenied".equals(ase.getErrorCode())) {
      return true;
    }
    if (ase.getStatusCode() == Constants.NO_SUCH_BUCKET_STATUS_CODE) {
      return false;
    }
    throw ase;
  }
}

代码示例来源:origin: aws/aws-sdk-java

@Override
public BucketWebsiteConfiguration getBucketWebsiteConfiguration(GetBucketWebsiteConfigurationRequest getBucketWebsiteConfigurationRequest)
    throws SdkClientException, AmazonServiceException {
  getBucketWebsiteConfigurationRequest = beforeClientExecution(getBucketWebsiteConfigurationRequest);
  rejectNull(getBucketWebsiteConfigurationRequest, "The request object parameter getBucketWebsiteConfigurationRequest must be specified.");
  String bucketName = getBucketWebsiteConfigurationRequest.getBucketName();
  rejectNull(bucketName,
    "The bucket name parameter must be specified when requesting a bucket's website configuration");
  Request<GetBucketWebsiteConfigurationRequest> request = createRequest(bucketName, null, getBucketWebsiteConfigurationRequest, HttpMethodName.GET);
  request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetBucketWebsite");
  request.addParameter("website", null);
  request.addHeader("Content-Type", "application/xml");
  try {
    return invoke(request, new Unmarshallers.BucketWebsiteConfigurationUnmarshaller(), bucketName, null);
  } catch (AmazonServiceException ase) {
    if (ase.getStatusCode() == 404) return null;
    throw ase;
  }
}

代码示例来源:origin: aws/aws-sdk-java

@Override
public BucketPolicy getBucketPolicy(
    GetBucketPolicyRequest getBucketPolicyRequest)
    throws SdkClientException, AmazonServiceException {
  getBucketPolicyRequest = beforeClientExecution(getBucketPolicyRequest);
  rejectNull(getBucketPolicyRequest,
    "The request object must be specified when getting a bucket policy");
  String bucketName = getBucketPolicyRequest.getBucketName();
  rejectNull(bucketName,
    "The bucket name must be specified when getting a bucket policy");
  Request<GetBucketPolicyRequest> request = createRequest(bucketName, null, getBucketPolicyRequest, HttpMethodName.GET);
  request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetBucketPolicy");
  request.addParameter("policy", null);
  BucketPolicy result = new BucketPolicy();
  try {
    String policyText = invoke(request, new S3StringResponseHandler(), bucketName, null);
    result.setPolicyText(policyText);
    return result;
  } catch (AmazonServiceException ase) {
    /*
     * If we receive an error response telling us that no policy has
     * been set for this bucket, then instead of forcing the user to
     * deal with the exception, we'll just return an empty result. Any
     * other exceptions will be rethrown for the user to handle.
     */
    if (ase.getErrorCode().equals("NoSuchBucketPolicy")) return result;
    throw ase;
  }
}

代码示例来源:origin: aws/aws-sdk-java

@Override
public AmazonServiceException handle(HttpResponse response) throws Exception {
  final AmazonServiceException ase = handleAse(response);
  ase.setStatusCode(response.getStatusCode());
  ase.setServiceName(response.getRequest().getServiceName());
  awsRequestMetrics.addPropertyWith(AWSRequestMetrics.Field.AWSRequestID, ase.getRequestId())
      .addPropertyWith(AWSRequestMetrics.Field.AWSErrorCode, ase.getErrorCode())
      .addPropertyWith(AWSRequestMetrics.Field.StatusCode, ase.getStatusCode());
  return ase;
}

代码示例来源:origin: aws-amplify/aws-sdk-android

@Test
public void testHandleErrorResponseHandlerFailsWith413() throws IOException {
  Request<?> request = new DefaultRequest<String>("ServiceName");
  final HttpResponse httpResponse = new HttpResponse.Builder().statusText("TestResponse")
      .statusCode(413).build();
  HttpResponseHandler<AmazonServiceException> errorResponseHandler = new HttpResponseHandler<AmazonServiceException>() {
    @Override
    public AmazonServiceException handle(HttpResponse response) throws Exception {
      assertSame(response, httpResponse);
      throw new Exception("test");
    }
    @Override
    public boolean needsConnectionLeftOpen() {
      return false;
    }
  };
  AmazonServiceException e = client.handleErrorResponse(request, errorResponseHandler,
      httpResponse);
  assertEquals(e.getStatusCode(), 413);
  assertEquals(e.getErrorCode(), "Request entity too large");
  assertEquals(e.getErrorType(), ErrorType.Client);
  assertEquals(e.getServiceName(), "ServiceName");
}

代码示例来源:origin: aws-amplify/aws-sdk-android

@Override
public BucketWebsiteConfiguration getBucketWebsiteConfiguration(
    GetBucketWebsiteConfigurationRequest getBucketWebsiteConfigurationRequest)
    throws AmazonClientException, AmazonServiceException {
  final String bucketName = getBucketWebsiteConfigurationRequest.getBucketName();
  assertParameterNotNull(bucketName,
      "The bucket name parameter must be specified when requesting a bucket's website configuration");
  final Request<GetBucketWebsiteConfigurationRequest> request = createRequest(bucketName, null,
      getBucketWebsiteConfigurationRequest, HttpMethodName.GET);
  request.addParameter("website", null);
  request.addHeader("Content-Type", "application/xml");
  try {
    return invoke(request, new Unmarshallers.BucketWebsiteConfigurationUnmarshaller(),
        bucketName, null);
  } catch (final AmazonServiceException ase) {
    if (ase.getStatusCode() == 404) {
      return null;
    }
    throw ase;
  }
}

代码示例来源:origin: stackoverflow.com

try {
  AmazonS3 s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
  String bucketName = getBucketName();
  s3.createBucket(bucketName);
  S3Object object = s3.getObject(bucketName, getKey());
} catch (AmazonServiceException e) {
  String errorCode = e.getErrorCode();
  if (!errorCode.equals("NoSuchKey")) {
    throw e;
  }
  Logger.getLogger(getClass()).debug("No such key!!!", e);
}

代码示例来源:origin: apache/nifi

/**
 * Populate exception attributes in the flow file
 * @param session process session
 * @param flowFile the flow file
 * @param exception exception thrown during invocation
 * @return FlowFile the updated flow file
 */
private FlowFile populateExceptionAttributes(final ProcessSession session, FlowFile flowFile,
    final AmazonServiceException exception) {
  Map<String,String> attributes = new HashMap<>();
  attributes.put(AWS_LAMBDA_EXCEPTION_MESSAGE, exception.getErrorMessage());
  attributes.put(AWS_LAMBDA_EXCEPTION_ERROR_CODE, exception.getErrorCode());
  attributes.put(AWS_LAMBDA_EXCEPTION_REQUEST_ID, exception.getRequestId());
  attributes.put(AWS_LAMBDA_EXCEPTION_STATUS_CODE, Integer.toString(exception.getStatusCode()));
  if ( exception.getCause() != null )
    attributes.put(AWS_LAMBDA_EXCEPTION_CAUSE, exception.getCause().getMessage());
  attributes.put(AWS_LAMBDA_EXCEPTION_ERROR_TYPE, exception.getErrorType().toString());
  attributes.put(AWS_LAMBDA_EXCEPTION_MESSAGE, exception.getErrorMessage());
  flowFile = session.putAllAttributes(flowFile, attributes);
  return flowFile;
}

代码示例来源:origin: aws/aws-sdk-java

/**
 * Takes the response exception and determines whether this exception matches the expected exception, by
 * comparing the respective error codes.
 * 
 * @param e
 *        Response Exception
 * @return True if it matches, False otherwise
 */
@Override
public boolean matches(AmazonServiceException e) {
  return "InvalidTarget".equals(e.getErrorCode());
}

代码示例来源:origin: aws/aws-sdk-java

throw new AmazonClientException("Unrecognized service response for the dry-run request.");
} catch (AmazonServiceException ase) {
  if (ase.getErrorCode().equals("DryRunOperation") && ase.getStatusCode() == 412) {
    return new DryRunResult<X>(true, request, ase.getMessage(), ase);
  } else if (ase.getErrorCode().equals("UnauthorizedOperation") && ase.getStatusCode() == 403) {
    return new DryRunResult<X>(false, request, ase.getMessage(), ase);
  } else if (ase.getErrorCode().equals("AuthFailure")) {
    return new DryRunResult<X>(false, request, ase.getMessage(), ase);

代码示例来源:origin: aws/aws-sdk-java

/**
 * Asserts that the specified AmazonServiceException is valid, meaning it has a non-empty,
 * non-null value for its message, requestId, etc.
 *
 * @param e
 *            The exception to validate.
 */
public static void assertValidException(AmazonServiceException e) {
  assertNotNull(e.getRequestId());
  assertTrue(e.getRequestId().trim().length() > 0);
  assertNotNull(e.getMessage());
  assertTrue(e.getMessage().trim().length() > 0);
  assertNotNull(e.getErrorCode());
  assertTrue(e.getErrorCode().trim().length() > 0);
  assertNotNull(e.getServiceName());
  assertTrue(e.getServiceName().startsWith("Amazon") || e.getServiceName().startsWith("AWS"));
}

代码示例来源:origin: aws/aws-sdk-java

@Override
public AmazonServiceException handle(HttpResponse errorResponse) throws Exception {
  AmazonServiceException ase = createAse(errorResponse);
  if (ase == null) {
    throw new SdkClientException("Unable to unmarshall error response from service");
  }
  ase.setHttpHeaders(errorResponse.getHeaders());
  if (StringUtils.isNullOrEmpty(ase.getErrorCode())) {
    ase.setErrorCode(errorResponse.getStatusCode() + " " + errorResponse.getStatusText());
  }
  return ase;
}

代码示例来源:origin: aws/aws-sdk-java

/**
 * Returns true if the specified exception is a retryable service side exception.
 *
 * @param exception The exception to test.
 * @return True if the exception resulted from a retryable service error, otherwise false.
 */
public static boolean isRetryableServiceException(SdkBaseException exception) {
  if (!isAse(exception)) {
    return false;
  }
  AmazonServiceException ase = toAse(exception);
  return RETRYABLE_STATUS_CODES.contains(ase.getStatusCode()) || RETRYABLE_ERROR_CODES.contains(ase.getErrorCode());
}

代码示例来源:origin: aws-amplify/aws-sdk-android

@Test
public void testDefaultErrorResponseHandlerCannotGetContent() throws Exception {
  List<Unmarshaller<AmazonServiceException, Node>> unmarshallerList = new ArrayList<Unmarshaller<AmazonServiceException, Node>>();
  HttpResponse errorResponse = new HttpResponse.Builder()
      .statusCode(400)
      .statusText("Error")
      .content(new InputStream() {
        @Override
        public int read() throws IOException {
          throw new IOException("Test IOException");
        }
      })
      .build();
  DefaultErrorResponseHandler handler = new DefaultErrorResponseHandler(unmarshallerList);
  AmazonServiceException e = handler.handle(errorResponse);
  assertEquals(e.getErrorCode(),
      errorResponse.getStatusCode() + " " + errorResponse.getStatusText());
  assertEquals(e.getStatusCode(), 400);
  assertEquals(e.getErrorType(), ErrorType.Unknown);
}

代码示例来源:origin: apache/ignite

S3Object obj = s3.getObject(bucketName, key);
if (e.getStatusCode() != 404)
  throw e;

相关文章