A Common Pitfall in AEM Development: Misplaced Trust in resolver.getResource() | Community
Skip to main content
divanshug
Adobe Champion
Adobe Champion
November 27, 2023

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

  • November 27, 2023
  • 1 reply
  • 514 views

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

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.

1 reply

kautuk_sahni
Community Manager
Community Manager
January 8, 2024

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

Kautuk Sahni