ApexSensei

Drills › Debug it

Fix a missing null check

Debug it · Intermediate · 10 min · Runs in your Salesforce Developer org · Apex Path

Scenario. The marketing team imports Leads from events, and about half arrive without an email. Since Friday, every import fails with one error.

A Lead trigger tidies email addresses, but one blank Email makes the whole insert fail. Read the error and fix it.

What you will learn

The most common Apex error is Attempt to de-reference a null object. It happens when you call a method on a blank field, such as lead.Email.toLowerCase() when Email was never filled in.

In a trigger one blank field throws inside the loop, and Salesforce rolls back every record in the batch, not just the bad one.

if (String.isBlank(lead.Email)) {
    continue;
}

Gotcha. String.isBlank covers null, empty text and spaces. lead.Email == '' misses null.

The task

Fix the handler so Leads with a blank Email are skipped, and every other Lead still gets its domain in Description.

Examples:

  • Email [email protected] → Description Domain: example.com
  • Email blank, Description Keep me → both stay exactly as they were
  • 200 Leads, half with no Email → all 200 insert, half get a domain

Requirements:

  1. Skip any Lead whose Email is blank. Leave its Email and Description alone.
  2. Keep the lowercasing the handler already does, and put the lowercase domain in Description (Salesforce stores Email in lowercase either way, but the call stays a safe habit).
  3. Set Description to Domain: followed by the part after @.
  4. Do not change what the handler does for Leads that already worked.

Starter code

public class AS_A276BDF2054F_EmailTidy {
    public static void beforeInsert(List<Lead> leads) {
        for (Lead lead : leads) {
            String email = lead.Email.toLowerCase();
            lead.Email = email;
            lead.Description = 'Domain: ' + email.substringAfter('@');
        }
    }
}

When it passes

Leads without an email insert untouched. Leads with an email get it lowercased and the domain in Description, one record or 200.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

Fix a query that finds no rows ›