Error Handling and Refreshing Apex-Backed Data
By the end of this lesson, you'll be able to:
- Use AuraHandledException to send a meaningful error message from Apex to LWC
- Catch and display Apex errors gracefully in a component
- Refresh Apex-backed wire data after a write operation
Prerequisites: "Wrapper and DTO Patterns for Apex Responses"
AuraHandledException
@AuraEnabled
public static void createOrder(String accountId) {
if (String.isBlank(accountId)) {
throw new AuraHandledException('An Account is required to create an Order.');
}
// ... create the order
}
By default, Salesforce strips the details off most exceptions before they reach the client, for security — a plain DmlException's real message never reaches JavaScript. AuraHandledException is the deliberate exception built for this exact purpose: its message is preserved and passed through to the component.
Catching Errors in LWC
try {
await createOrder({ accountId: this.selectedAccountId });
} catch (error) {
this.errorMessage = error.body?.message ?? 'An unexpected error occurred.';
}
For an imperative call, wrap it in try/catch as usual. For a @wire-based read, the wired result carries an error property directly (this.wiredResult.error) rather than throwing.
refreshApex Revisited
import { refreshApex } from '@salesforce/apex';
async handleSave() {
await updateOpportunityStage({ opportunityId: this.recordId, stage: 'Closed Won' });
await refreshApex(this.wiredOpportunities);
}
The same refreshApex pattern from Module 6, Lesson 5 applies directly here — after a write via an imperative Apex call, a wired Apex read won't automatically know to re-fetch, so refreshApex forces it to pick up the change.
Exercise
Write an Apex method deleteOrder(Id orderId) that throws an AuraHandledException with the message "Order not found." if the given orderId does not correspond to an existing Order.
Show hint
Query for the record; throw if not found.
Exercise
Challenge: explain, as a comment, why a plain DmlException thrown from Apex does not show its real message in the LWC catch block by default.
Show hint
Think about the security reasoning behind this behavior.
Error Handling and Refreshing Apex-Backed Data 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
AuraHandledException is the only way to send a custom, catchable error message from Apex to LWC — every other exception type gets stripped down to a generic message for security reasons.