Enhance AWS calls using request handlers

Using the SDK, you can extend an AWS request with a piece of code that is going to be executed at a certain point during the lifecycle call. This is not something you’ll use frequently, but at least it worth to know it could be done, even it’s not very well documented and there are not so many examples you can find.
Let’s see below what are the steps you have to do in order to add a hook to an AWS call:
1. Extend the RequestHandler2 class and override the methods where you want to add some processing logic

public class TestHandler extends RequestHandler2 {

    @Override
    public AmazonWebServiceRequest beforeMarshalling(AmazonWebServiceRequest request) {

        System.out.println("beforeMarshalling");
        return request;
    }

    @Override
    public void beforeRequest(Request<?> request) {

        System.out.println("beforeRequest");
    }

    @Override
    public HttpResponse beforeUnmarshalling(Request<?> request, HttpResponse httpResponse) {

        System.out.println("beforeUnmarshalling");
        return httpResponse;
    }

    @Override
    public void afterResponse(Request<?> request, Response<?> response) {

        System.out.println("afterResponse");
    }

    @Override
    public void afterError(Request<?> request, Response<?> response, Exception e) {

        System.out.println("afterError");
    }
}

2. Add the new handler to the AWS client.

public static void main(String[] args) {  
    AWSCredentials credentials = new SystemPropertiesCredentialsProvider().getCredentials(); 
    AmazonDynamoDBClient dynamoDB = new AmazonDynamoDBClient(credentials);  
      
    dynamoDB.addRequestHandler(new TestHandler());  
      
    dynamoDB.listTables();  
    System.out.println("-----");  
    dynamoDB.describeTable("unexistent-table");  
}

This code snippet is available here. Let’s run now this piece of code and see the result:

beforeMarshalling 
beforeRequest 
beforeUnmarshalling 
afterResponse 
----- 
beforeMarshalling 
beforeRequest 
Exception in thread "main" com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException: Requested resource not found: Table: unexistent-table not found

The output is self-explanatory, so we are not going to add more details here. To sum up, you should keep in mind this feature exists and if it could help to develop your app, consider this post as an example. Let us know if you have any question and don’t forget to become a member of our community by subscribing to our newsletter!