Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.

A Common Pitfall in AEM Development: Misplaced Trust in resolver.getResource()

Avatar

Level 3

11/26/23

Overview

Hello AEM Enthusiasts,

Today, I want to shine a light on a subtle yet significant oversight that we, as AEM developers, often commit - an unwavering trust in the resolver.getResource() API.

It's common practice to retrieve resources using this API and proceed on the assumption that if it's not null, it's valid. But here's the catch: resolver.getResource() can return a NonExistingResource object even when the actual resource doesn't exist in the repository!

Consider this scenario: You're developing a component that fetches an image resource. Here's a snippet we've all written at some point:

Resource imageResource = resolver.getResource(imagePath);
if (imageResource != null) {
    // Proceed with using imageResource
}

Looks familiar, right? But what if imagePath is incorrect or the resource has been moved? The API doesn't return null; instead, it gives us a NonExistingResource that passes our null check and leads to unexpected behaviour or down the line.

So what should we do? Simple - validate the resource:

Resource imageResource = resolver.getResource(imagePath);
if (imageResource != null && !ResourceUtil.isNonExistingResource(imageResource)) {
    // The resource is valid, proceed with confidence
}

By implementing this additional check, we can prevent those tricky bugs that arise from invalid resources, ensuring our components behave reliably.

Let's spread the word about this best practice and save our future selves from debugging headaches!

 

Q&A

Please use this thread to ask questions relating to this article

1 Comment

Avatar

Administrator

1/7/24

@divanshug this is a nice read. Thank you for sharing.