Handling Errors Gracefully for the UI
By the end of this lesson, you'll be able to:
- Throw an AuraHandledException with a message safe to show a user
- Explain why a generic Apex exception message shouldn't reach the UI directly
- Apply Module 30's error-handling checklist one final time, at the UI boundary
Prerequisites: "Cacheable Methods and Performance"
Why a raw exception message is often the wrong thing to show a user
@AuraEnabled
public static void saveOpportunity(Opportunity opp) {
update opp; // if this throws, the raw DmlException message reaches the UI
}
An unhandled DmlException here could surface a raw, technical message straight to the end user — something like a field-level API name or an internal validation-rule identifier, neither of which means anything to someone using the UI, and which might even leak internal implementation details unnecessarily.
Throwing AuraHandledException with a clear message
@AuraEnabled
public static void saveOpportunity(Opportunity opp) {
try {
update opp;
} catch (DmlException e) {
AuraHandledException ex = new AuraHandledException('Could not save the opportunity. Please check the required fields and try again.');
ex.setMessage('Could not save the opportunity. Please check the required fields and try again.');
throw ex;
}
}
AuraHandledException is specifically designed to carry a message safely across the Apex-to-LWC boundary — catching the real, technical exception (Module 13's try/catch) and re-throwing this UI-safe version with a clear, human-readable message instead. (The message must be set both in the constructor and via setMessage() due to a well-known Apex quirk with how this specific exception type serializes its message.)
Module 30's checklist, at the final boundary
This closes out the same discipline Module 30's "review and refactor" lesson applied to Case routing — validated input, bulk-safe logic, deliberate sharing, and errors handled gracefully — now applied specifically at the point where Apex hands control back to a UI a real user is looking at. A method exposed to an LWC deserves every one of those checks, since it's directly reachable by anyone using the application.
Exercise
Wrap this method's DML in a try/catch that throws an AuraHandledException with a user-friendly message on failure.
Show hint
catch (DmlException e) { throw new AuraHandledException(...); }
Handling Errors Gracefully for the UI 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
This closing lesson covers AuraHandledException — the specific exception type designed to carry a safe, UI-appropriate message back to the component that called into Apex.