AWS DynamoDB's GetItemResult.getItem
can be null if the item is not found in the database. DynamoDB.getItem
does not throw an exception when a returned item is null, so we recommend checking if the value before accessing it.
1public void dynamoDBGetItemNoncompliant(Map<String, AttributeValue> key, String tableName) {
2 AmazonDynamoDB dynamoDBClient = AmazonDynamoDBClientBuilder.standard().build();
3 GetItemRequest request = new GetItemRequest()
4 .withTableName(tableName)
5 .withKey(key);
6 try {
7 GetItemResult result = dynamoDBClient.getItem(request);
8 // Noncompliant: result is not null-checked.
9 System.out.println(result.getItem().get("key"));
10 } catch (ResourceNotFoundException e) {
11 log.error(e.getMessage());
12 }
13}
1public void dynamoDBGetItemCompliant(Map<String, AttributeValue> key, String tableName) {
2 AmazonDynamoDB dynamoDBClient = AmazonDynamoDBClientBuilder.standard().build();
3 GetItemRequest request = new GetItemRequest()
4 .withTableName(tableName)
5 .withKey(key);
6 try {
7 GetItemResult result = dynamoDBClient.getItem(request);
8 // Compliant: result is null-checked.
9 if (result.getItem() != null) {
10 System.out.println(result.getItem().get("key"));
11 }
12 } catch (ResourceNotFoundException e) {
13 log.error(e.getMessage());
14 }
15}