or run

tessl search
Log in

Version

Files

docs

amazon-cloudwatch.mdamazon-dynamodb.mdamazon-ec2.mdamazon-s3.mdauthentication.mdaws-iam.mdaws-lambda.mdclient-management.mderror-handling.mdindex.md
tile.json

error-handling.mddocs/

Error Handling

Structured exception hierarchy for handling AWS service errors, client-side errors, and network issues with detailed error information.

Capabilities

Base Exception Hierarchy

Root exception classes providing the foundation for all AWS SDK error handling.

/**
 * Base exception for all AWS SDK exceptions
 * Root of the exception hierarchy
 */
public class SdkBaseException extends RuntimeException {
    /**
     * Creates a base SDK exception
     * @param message Error message
     */
    public SdkBaseException(String message);
    
    /**
     * Creates a base SDK exception with cause
     * @param message Error message
     * @param cause Underlying cause
     */
    public SdkBaseException(String message, Throwable cause);
    
    /**
     * Gets the error message
     * @return Error message
     */
    public String getMessage();
    
    /**
     * Gets the underlying cause
     * @return Underlying throwable or null
     */
    public Throwable getCause();
}

/**
 * Base client exception for AWS SDK operations
 * Base class for client-side and service-side errors
 */
public class AmazonClientException extends SdkBaseException {
    /**
     * Creates an Amazon client exception
     * @param message Error message
     */
    public AmazonClientException(String message);
    
    /**
     * Creates an Amazon client exception with cause
     * @param message Error message
     * @param cause Underlying cause
     */
    public AmazonClientException(String message, Throwable cause);
}

/**
 * Client-side exceptions (local errors)
 * Network issues, validation errors, configuration problems
 */
public class SdkClientException extends AmazonClientException {
    /**
     * Creates a client-side exception
     * @param message Error message
     */
    public SdkClientException(String message);
    
    /**
     * Creates a client-side exception with cause
     * @param message Error message
     * @param cause Underlying cause
     */
    public SdkClientException(String message, Throwable cause);
}

Service-Side Exceptions

Exceptions for errors returned by AWS services with detailed error information.

/**
 * Service-side exceptions (AWS service errors)
 * Contains detailed error information from AWS services
 */
public class AmazonServiceException extends AmazonClientException {
    /**
     * Creates a service exception
     * @param message Error message from the service
     */
    public AmazonServiceException(String message);
    
    /**
     * Creates a service exception with cause
     * @param message Error message
     * @param cause Underlying cause
     */
    public AmazonServiceException(String message, Throwable cause);
    
    /**
     * Gets the AWS-specific error code
     * @return Error code (e.g., "NoSuchBucket", "ValidationException")
     */
    public String getErrorCode();
    
    /**
     * Sets the AWS error code
     * @param errorCode AWS error code
     */
    public void setErrorCode(String errorCode);
    
    /**
     * Gets the unique request ID for support and debugging
     * @return Request ID
     */
    public String getRequestId();
    
    /**
     * Sets the request ID
     * @param requestId Unique request identifier
     */
    public void setRequestId(String requestId);
    
    /**
     * Gets the HTTP status code
     * @return HTTP status code (e.g., 400, 403, 404, 500)
     */
    public int getStatusCode();
    
    /**
     * Sets the HTTP status code
     * @param statusCode HTTP status code
     */
    public void setStatusCode(int statusCode);
    
    /**
     * Gets the error type classification
     * @return Error type (Client, Service, or Unknown)
     */
    public ErrorType getErrorType();
    
    /**
     * Sets the error type
     * @param errorType Error type classification
     */
    public void setErrorType(ErrorType errorType);
    
    /**
     * Gets the AWS service name that generated the error
     * @return Service name (e.g., "Amazon S3", "Amazon EC2")
     */
    public String getServiceName();
    
    /**
     * Sets the service name
     * @param serviceName AWS service name
     */
    public void setServiceName(String serviceName);
    
    /**
     * Gets additional error details from HTTP response headers
     * @return Map of additional error information
     */
    public Map<String, String> getErrorDetails();
    
    /**
     * Error type enumeration
     */
    public enum ErrorType {
        /** Client-side error (4xx status codes) */
        Client,
        /** Service-side error (5xx status codes) */
        Service,
        /** Unknown error type */
        Unknown
    }
}

Usage Examples:

import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;

try {
    // AWS operation that might fail
    s3Client.getObject("non-existent-bucket", "some-key");
    
} catch (AmazonServiceException e) {
    // Handle service-side errors
    System.err.println("AWS Service Error:");
    System.err.println("  Error Code: " + e.getErrorCode());
    System.err.println("  Error Type: " + e.getErrorType());
    System.err.println("  Request ID: " + e.getRequestId());
    System.err.println("  Status Code: " + e.getStatusCode());
    System.err.println("  Service: " + e.getServiceName());
    System.err.println("  Message: " + e.getMessage());
    
    // Handle specific error codes
    switch (e.getErrorCode()) {
        case "NoSuchBucket":
            System.err.println("The specified bucket does not exist");
            break;
        case "NoSuchKey":
            System.err.println("The specified key does not exist");
            break;
        case "AccessDenied":
            System.err.println("Access denied - check your permissions");
            break;
        default:
            System.err.println("Unexpected service error: " + e.getErrorCode());
    }
    
} catch (SdkClientException e) {
    // Handle client-side errors
    System.err.println("Client Error: " + e.getMessage());
    
    if (e.getCause() instanceof java.net.UnknownHostException) {
        System.err.println("Network connectivity issue");
    } else if (e.getCause() instanceof java.net.SocketTimeoutException) {
        System.err.println("Request timeout - try again later");
    }
}

Specialized Client Exceptions

Specific client-side exceptions for common error scenarios.

/**
 * Exception for request timeout scenarios
 */
public class ClientExecutionTimeoutException extends SdkClientException {
    /**
     * Creates a timeout exception
     * @param message Error message
     */
    public ClientExecutionTimeoutException(String message);
    
    /**
     * Creates a timeout exception with cause
     * @param message Error message
     * @param cause Underlying cause
     */
    public ClientExecutionTimeoutException(String message, Throwable cause);
}

/**
 * Exception for operation cancellation
 */
public class AbortedException extends SdkClientException {
    /**
     * Creates an aborted exception
     * @param message Error message
     */
    public AbortedException(String message);
    
    /**
     * Creates an aborted exception with cause
     * @param message Error message
     * @param cause Underlying cause
     */
    public AbortedException(String message, Throwable cause);
}

/**
 * Exception for retry exhaustion
 */
public class ResetException extends SdkClientException {
    /**
     * Creates a reset exception
     * @param message Error message
     */
    public ResetException(String message);
    
    /**
     * Creates a reset exception with cause
     * @param message Error message
     * @param cause Underlying cause
     */
    public ResetException(String message, Throwable cause);
}

Service-Specific Exceptions

Service-specific exception types for detailed error handling.

/**
 * Base class for Amazon S3 exceptions
 */
public class AmazonS3Exception extends AmazonServiceException {
    /**
     * Creates an S3 exception
     * @param message Error message
     */
    public AmazonS3Exception(String message);
    
    /**
     * Gets additional S3-specific error details
     * @return Map of S3 error details
     */
    public Map<String, String> getAdditionalDetails();
}

/**
 * Base class for Amazon EC2 exceptions
 */
public class AmazonEC2Exception extends AmazonServiceException {
    /**
     * Creates an EC2 exception
     * @param message Error message
     */
    public AmazonEC2Exception(String message);
}

/**
 * Base class for Amazon DynamoDB exceptions
 */
public class AmazonDynamoDBException extends AmazonServiceException {
    /**
     * Creates a DynamoDB exception
     * @param message Error message
     */
    public AmazonDynamoDBException(String message);
}

/**
 * DynamoDB conditional check failed exception
 */
public class ConditionalCheckFailedException extends AmazonDynamoDBException {
    /**
     * Creates a conditional check failed exception
     * @param message Error message
     */
    public ConditionalCheckFailedException(String message);
}

/**
 * DynamoDB provisioned throughput exceeded exception
 */
public class ProvisionedThroughputExceededException extends AmazonDynamoDBException {
    /**
     * Creates a throughput exceeded exception
     * @param message Error message
     */
    public ProvisionedThroughputExceededException(String message);
}

/**
 * DynamoDB resource not found exception
 */
public class ResourceNotFoundException extends AmazonDynamoDBException {
    /**
     * Creates a resource not found exception
     * @param message Error message
     */
    public ResourceNotFoundException(String message);
}

Legacy Exception Classes

Deprecated exception classes maintained for backward compatibility.

/**
 * @deprecated Use SdkClientException instead
 * Legacy client exception class
 */
@Deprecated
public class AmazonClientException extends SdkClientException {
    /**
     * Creates a client exception
     * @param message Error message
     */
    public AmazonClientException(String message);
    
    /**
     * Creates a client exception with cause
     * @param message Error message
     * @param cause Underlying cause
     */
    public AmazonClientException(String message, Throwable cause);
}

Error Handling Best Practices

Common patterns for handling AWS SDK exceptions effectively.

Usage Examples:

import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.dynamodbv2.model.*;

// S3 error handling example
try {
    S3Object object = s3Client.getObject("my-bucket", "my-key");
    // Process object...
    
} catch (AmazonS3Exception e) {
    switch (e.getErrorCode()) {
        case "NoSuchBucket":
            // Create bucket or use different bucket
            createBucketIfNotExists("my-bucket");
            break;
        case "NoSuchKey":
             // Handle missing object
            System.out.println("Object not found: " + e.getMessage());
            break;
        case "AccessDenied":
            // Check credentials and permissions
            System.err.println("Access denied. Check IAM permissions.");
            break;
        default:
            // Log unexpected errors with request ID for support
            System.err.println("S3 Error [" + e.getRequestId() + "]: " + 
                             e.getErrorCode() + " - " + e.getMessage());
    }
} catch (SdkClientException e) {
    // Handle network/client issues
    System.err.println("Client error: " + e.getMessage());
    // Implement retry logic for transient errors
}

// DynamoDB error handling example
try {
    dynamoClient.putItem(putItemRequest);
    
} catch (ConditionalCheckFailedException e) {
    // Handle condition failures (e.g., item already exists)
    System.out.println("Conditional check failed: " + e.getMessage());
    
} catch (ProvisionedThroughputExceededException e) {
    // Handle rate limiting - implement exponential backoff
    System.out.println("Rate limited - backing off...");
    Thread.sleep(calculateBackoffDelay(retryCount));
    
} catch (ResourceNotFoundException e) {
    // Handle missing table/index
    System.err.println("Resource not found: " + e.getMessage());
    
} catch (AmazonDynamoDBException e) {
    // Handle other DynamoDB errors
    System.err.println("DynamoDB error: " + e.getErrorCode() + 
                      " - " + e.getMessage());
}

// Generic error handling pattern
try {
    // AWS operation
    performAwsOperation();
    
} catch (AmazonServiceException e) {
    // Service errors - log with request ID for AWS support
    logServiceError(e);
    
    // Handle based on error type
    if (e.getErrorType() == AmazonServiceException.ErrorType.Client) {
        // 4xx errors - fix request and don't retry
        handleClientError(e);
    } else {
        // 5xx errors - may be retryable
        handleServiceError(e);
    }
    
} catch (SdkClientException e) {
    // Client errors - network, timeout, configuration
    logClientError(e);
    
    if (isRetryableClientError(e)) {
        // Implement retry with exponential backoff
        retryWithBackoff(() -> performAwsOperation());
    } else {
        // Non-retryable error - fix configuration
        handleNonRetryableError(e);
    }
}

Retry and Error Recovery

Utilities and patterns for implementing retry logic and error recovery.

/**
 * Utility methods for error analysis and retry decisions
 */
public class AwsErrorUtils {
    /**
     * Determines if an exception is retryable
     * @param exception Exception to analyze
     * @return true if the error is retryable
     */
    public static boolean isRetryableServiceException(AmazonServiceException exception) {
        // 5xx status codes are generally retryable
        if (exception.getStatusCode() >= 500) {
            return true;
        }
        
        // Some 4xx errors are retryable (throttling)
        String errorCode = exception.getErrorCode();
        return "Throttling".equals(errorCode) || 
               "ThrottledException".equals(errorCode) ||
               "ProvisionedThroughputExceededException".equals(errorCode);
    }
    
    /**
     * Calculates exponential backoff delay
     * @param retryCount Number of retries attempted
     * @return Delay in milliseconds
     */
    public static long calculateBackoffDelay(int retryCount) {
        // Exponential backoff: 100ms * 2^retryCount + jitter
        long baseDelay = 100L * (1L << retryCount);
        long jitter = (long) (Math.random() * baseDelay * 0.1);
        return Math.min(baseDelay + jitter, 30000); // Cap at 30 seconds
    }
    
    /**
     * Extracts meaningful error summary for logging
     * @param exception Service exception
     * @return Error summary string
     */
    public static String getErrorSummary(AmazonServiceException exception) {
        return String.format("%s [%s] - %s (RequestId: %s)", 
                           exception.getServiceName(),
                           exception.getErrorCode(),
                           exception.getMessage(),
                           exception.getRequestId());
    }
}

Types

/**
 * Error response information from AWS services
 */
public class ErrorResponse {
    public String getCode();
    public String getMessage();
    public String getType();
    public String getDetail();
}

/**
 * Request context for error analysis
 */
public class RequestContext {
    public String getRequestId();
    public String getServiceName();
    public String getOperationName();
    public Date getRequestTime();
    public int getAttemptCount();
}