Advanced 25 min read

Handle Edge Cases

By the end of this lesson, you'll be able to:

  • Handle an Account with zero Cases, zero Contacts, or no won Opportunities
  • Handle an invalid or null accountId gracefully
  • Write tests confirming each edge case behaves correctly, not just the happy path

Prerequisites: "Write Comprehensive Tests"

The zero-data Account

@isTest
static void newAccountWithNoDataReturnsZeroedSummary() {
    Account acc = new Account(Name = 'Brand New Account');
    insert acc;

    AccountHealthService service = new AccountHealthService();
    AccountHealthSummary summary = service.getHealthSummary(acc.Id);

    System.assertEquals(0, summary.openCaseCount);
    System.assertEquals(0, summary.averageResolutionDays);
    System.assertEquals(0, summary.totalWonRevenue);
}

Every method built in Lesson 2 already handles empty results gracefully (if (closedCases.isEmpty()) { return 0; }) — this test formally confirms that design decision, exactly Module 17's habit of testing the empty/zero case explicitly rather than assuming it "probably works."

A null or invalid accountId

@AuraEnabled(cacheable=true)
public static AccountHealthSummary getAccountHealth(Id accountId) {
    if (accountId == null) {
        AuraHandledException ex = new AuraHandledException('An account must be selected to view health data.');
        ex.setMessage('An account must be selected to view health data.');
        throw ex;
    }
    return new AccountHealthService().getHealthSummary(accountId);
}

This is Module 34's AuraHandledException lesson, applied to a genuinely real failure mode: an LWC could conceivably call this before a user has actually selected an Account — a clear, UI-safe message here is far better than whatever cryptic error a null Id would eventually cause deeper in the query logic.

Exercise

Write a test confirming getAccountHealth throws an AuraHandledException when called with a null accountId.

Show hint

Use the try/System.assert(false)/catch pattern from Module 31.

APEX

Handle Edge Cases Quiz

1. Why does a brand-new Account with zero Cases and Contacts deserve its own explicit test?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

A brand-new Account with no Cases, no Contacts, and no closed deals is a completely normal, expected scenario for this dashboard — this lesson makes sure it displays cleanly rather than breaking.