Sub topic 9
Handling Errors from the Save and the Refresh
This chapter assumes you can wire a cacheable Apex method, you know what the wired result object looks like, and you are comfortable with async/await. You have already seen the save-then-refresh pattern. Here we look at what can go wrong in each step and how to show the user a useful message.
Two calls, two ways to fail
The save-then-refresh pattern makes two separate asynchronous calls:
updateEmailruns a non-cacheable Apex method that performs DML.refreshApexasks the wire to fetch fresh data from the server.
Either call can fail, and the failures mean different things.
| Step | Typical cause | What the data looks like afterward |
|---|---|---|
| Save | Validation rule, missing field access, a trigger error, a record lock | The record is unchanged on the server. The cached list is still correct. |
| Refresh | Network failure, session timeout, the read query throwing an exception | The record is saved on the server. The list on screen is stale. |
If you treat both failures the same way, you can tell the user "Save failed" when the save actually worked. Keep the two cases apart.
Where errors come from
The imperative call to updateEmail returns a promise. If the Apex method throws an AuraHandledException, or an unhandled exception such as a DmlException, the promise rejects with an error object. The useful details are in error.body. Its shape varies, so a small helper that handles the common cases keeps your handler short.
export function reduceErrors(error) {
if (!error) {
return 'Unknown error';
}
if (typeof error === 'string') {
return error;
}
const body = error.body;
if (Array.isArray(body)) {
return body.map((e) => e.message).join(', ');
}
if (body && typeof body.message === 'string') {
return body.message;
}
if (typeof error.message === 'string') {
return error.message;
}
return 'Unknown error';
}The refreshApex promise rejects for its own reasons. A rejection there means the re-fetch failed, not the save.
Separating the two failures
Give each call its own try/catch. That lets you stop after a failed save, and it lets you report a failed refresh without hiding the successful save.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
import { reduceErrors } from './errorUtils';
export default class ContactListSafe extends LightningElement {
@api recordId;
saveError;
refreshError;
@wire(getContacts, { accountId: '$recordId' })
contacts;
async handleSave(event) {
const { contactId, email } = event.detail;
this.saveError = undefined;
this.refreshError = undefined;
try {
await updateEmail({ contactId, email });
} catch (e) {
this.saveError = reduceErrors(e);
return;
}
try {
await refreshApex(this.contacts);
} catch (e) {
this.refreshError = reduceErrors(e);
}
}
}The return inside the first catch matters. If the save fails, there is nothing new to fetch, so the component skips the refresh.
The component keeps saveError and refreshError apart from the wire's own contacts.error. The wire sets contacts.error when the wired read fails. The two imperative errors are yours to manage. Reusing one field for all three makes it hard to tell what failed.
<template>
<template lwc:if={saveError}>
<p>Could not save the change: {saveError}</p>
</template>
<template lwc:if={refreshError}>
<p>The change was saved, but the list could not be updated: {refreshError}</p>
</template>
<template lwc:if={contacts.error}>
<p>Could not load contacts.</p>
</template>
<template lwc:if={contacts.data}>
<template for:each={contacts.data} for:item="contact">
<p key={contact.Id}>{contact.Name}: {contact.Email}</p>
</template>
</template>
</template>The refresh message says the change was saved. That sentence is the reason for splitting the handlers.
Decision flow
Practical points
- Clear old errors at the start of each save. Otherwise a message from a previous attempt stays on screen.
- Do not call
refreshApexinside thecatchof the save. A failed save changed nothing. - On a refresh failure, a retry button that calls
refreshApex(this.contacts)again is usually enough. Do not save a second time.
Exercise
A user edits an email address and clicks save. The screen shows "Save failed", but when they reload the page, the new email is there. Which part of the handler most likely caused the wrong message, and how do you fix it?
Show answer
The save and the refresh share one try/catch, so a failure in refreshApex is reported as a failed save. The save actually succeeded. Fix it by giving updateEmail and refreshApex separate try/catch blocks, returning after a failed save, and showing a message such as "The change was saved, but the list could not be updated" when only the refresh fails.