Prevent null pointer exceptions by validating object chains before accessing nested properties. Use early returns with null checks instead of optional chaining when the rest of the function depends on a non-null value.
Example of problematic code:
const messages = user.account.access_token
? await getMessagesBatch(messageIds, user.account.access_token)
: [];
Better approach:
const accessToken = user.account?.access_token;
if (!accessToken) {
logger.warn("No access token available");
return [];
}
const messages = await getMessagesBatch(messageIds, accessToken);
Key practices:
This pattern improves code reliability by catching null cases early and explicitly, rather than letting them propagate through the codebase.
Enter the URL of a public GitHub repository