Error Handling and Optional Chaining
By the end of this lesson, you'll be able to:
- Use try/catch to handle errors from asynchronous code
- Use optional chaining (?.) to safely access nested properties
- Explain why this matters specifically for Salesforce wire data
Prerequisites: "Promises and async/await"
try/catch with async/await
async handleLoad() {
try {
this.accounts = await getAccounts();
} catch (error) {
this.error = error;
console.error('Failed to load accounts', error);
}
}
Wrapping an await call in try/catch lets you handle a rejected Promise gracefully — showing an error message to the user, for instance — instead of letting the failure crash silently or propagate unhandled.
Optional Chaining (?.)
const accountName = record?.Account?.Name;
If record or record.Account is null or undefined at any point in the chain, this safely evaluates to undefined instead of throwing a "Cannot read property of undefined" error. This is extremely common with Salesforce wire data, which is frequently null for a brief moment while it's still loading (Module 6).
The Nullish Coalescing Operator (??)
const displayName = record?.Account?.Name ?? 'Unknown Account';
?? pairs naturally with optional chaining — providing a fallback value specifically when the left side is null or undefined (unlike ||, which also triggers on other falsy values like an empty string or 0).
Why This Matters in Real Projects
Wire service data (Module 6) is commonly undefined before it finishes loading. A template or getter that assumes data is always present will throw errors during that loading window — optional chaining is the standard, idiomatic way to guard against exactly this.
Exercise
Rewrite this to safely handle a possibly-missing Account using optional chaining: const name = record.Account.Name;
Show hint
Add ?. after each property that might be missing.
Exercise
Challenge: explain, as a comment, why record?.Account?.Name ?? 'Unknown' is preferable to record?.Account?.Name || 'Unknown' in some cases.
Show hint
Think about what || treats as falsy versus what ?? treats as nullish.
Error Handling and Optional Chaining Quiz
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
Optional chaining prevents an entire category of runtime error that's especially common in LWC, where wire-service data is often null while it loads.