Sub topic 9
Handling errors from the save and the refresh
This chapter assumes you can already wire a cacheable Apex method, call a non-cacheable method imperatively with async/await, and use refreshApex after a save. It covers what happens when either step fails, and how to tell the user which one did.
Two steps, two ways to fail
The save-then-refresh pattern from the previous chapter has two separate operations:
- An imperative call to a non-cacheable Apex method that changes data.
- A call to
refreshApexthat asks the wire to fetch the data again.
Each can fail without the other, and the database state differs in each case.
| Stage that failed | State in the database | State on screen | What to tell the user |
|---|---|---|---|
| Save | Unchanged | Old data, which is still correct | The change was not saved, and why |
| Refresh, after a successful save | Changed | Old data, which is now stale | The change was saved, but the list could not be reloaded |
| Both succeed | Changed | New data | Confirmation |
One try/catch around both calls cannot tell the first two rows apart. "Could not save" is false when the save worked and only the reload failed. A user who sees it may save again, or may stop trusting the screen.
Errors from the save
An imperative Apex call returns a promise. If the Apex method throws, the promise rejects with an error object. For most exceptions, the useful text is not at error.message. Platform errors usually carry it at error.body.message. Validation and field errors can also appear in error.body.pageErrors or error.body.fieldErrors, depending on the exception type.
Which message reaches the browser depends on the exception you throw in Apex. An unhandled DmlException or QueryException gives the client a generic "An unexpected error occurred" style message and no detail. Throw an AuraHandledException with an explicit message if you want the user to see something specific.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
try {
Contact c = new Contact(Id = contactId, Email = email);
update as user c;
} catch (DmlException e) {
throw buildException(e.getDmlMessage(0));
}
}
private static AuraHandledException buildException(String message) {
AuraHandledException ex = new AuraHandledException(message);
// Without setMessage, getMessage() returns "Script-thrown exception",
// which matters in Apex tests even though the client sees the message.
ex.setMessage(message);
return ex;
}
}getDmlMessage(0) returns the message for the first failed row. This method updates one record, so the first message is the only one. A bulk method would loop over all of them.
Normalizing the error shape
Errors reach your component in several shapes: an object with body.message, an array of such objects, a JavaScript Error, or occasionally a string. A small helper keeps the handlers readable.
export function reduceErrors(error) {
if (!error) {
return 'Unknown error';
}
if (Array.isArray(error.body)) {
return error.body.map((e) => e.message).join(', ');
}
if (error.body && typeof error.body.message === 'string') {
return error.body.message;
}
if (typeof error.message === 'string') {
return error.message;
}
if (typeof error === 'string') {
return error;
}
return 'Unknown error';
}Put it in a shared utility module in your project and import it where needed. It is shown inline in the next example so the component runs as written.
Errors from the refresh
refreshApex returns a promise that settles when the refresh finishes. A refresh has two failure paths:
- The wire provisions a new result whose
erroris set. For a property wire this isthis.contacts.error. For a function wire, your handler receives it. - The promise returned by
refreshApexrejects, for example because the network call fails.
Do not assume only one of these occurs. Wrap the call in try/catch, and also render the wire's own error in the template. That way the screen reports a failed reload even if the promise resolves.
A failed refresh also changes what the user sees. When the wire provisions an error, contacts.data becomes undefined, and a template that checks contacts.data shows an empty area. The old rows disappear even though the save succeeded. That is a poor result for a transient network problem. Decide deliberately whether to keep showing the last good data. The function-wire variant later in this chapter shows how.
A complete handler
This component handles both stages separately, blocks double submission, and reports each outcome. It uses a property wire.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
function reduceErrors(error) {
if (!error) {
return 'Unknown error';
}
if (Array.isArray(error.body)) {
return error.body.map((e) => e.message).join(', ');
}
if (error.body && typeof error.body.message === 'string') {
return error.body.message;
}
if (typeof error.message === 'string') {
return error.message;
}
return typeof error === 'string' ? error : 'Unknown error';
}
export default class ContactListSafe extends LightningElement {
@api recordId;
isSaving = false;
message;
@wire(getContacts, { accountId: '$recordId' })
contacts;
get loadErrorText() {
return this.contacts && this.contacts.error
? reduceErrors(this.contacts.error)
: undefined;
}
async handleSave(event) {
if (this.isSaving) {
return;
}
this.isSaving = true;
this.message = undefined;
const { contactId, email } = event.detail;
try {
await updateEmail({ contactId, email });
} catch (error) {
this.message = 'Could not save the change: ' + reduceErrors(error);
this.isSaving = false;
return;
}
try {
await refreshApex(this.contacts);
this.dispatchEvent(
new ShowToastEvent({
title: 'Saved',
message: 'The email address was updated.',
variant: 'success'
})
);
} catch (error) {
this.message =
'The change was saved, but the list could not be reloaded: ' +
reduceErrors(error);
} finally {
this.isSaving = false;
}
}
}The return inside the first catch exits the method, so the refresh never runs after a failed save. Refreshing then would only waste a server call, because nothing changed. isSaving is cleared on both exit paths, so the next click is not blocked.
The matching template shows the three kinds of message separately.
<template>
<template lwc:if={message}>
<p role="alert">{message}</p>
</template>
<template lwc:if={loadErrorText}>
<p role="alert">Could not load contacts: {loadErrorText}</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>Keeping the last good data with a function wire
With a function wire you control what happens to your own fields. To keep the old rows visible after a failed reload, store the error in a separate field and leave contacts alone.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactListKeepData extends LightningElement {
@api recordId;
contacts;
loadError;
wiredContactsResult;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts(result) {
this.wiredContactsResult = result;
const { data, error } = result;
if (data) {
this.contacts = data;
this.loadError = undefined;
} else if (error) {
this.loadError = error;
// this.contacts is intentionally not cleared.
}
}
async reload() {
try {
await refreshApex(this.wiredContactsResult);
} catch (error) {
this.loadError = error;
}
}
}The trade-off is that the screen can now show data that is known to be stale. Pair this with a visible warning that the list may be out of date. Showing nothing is safer when stale values could mislead, for example balances or stock counts. Showing stale rows with a warning is friendlier for slow-changing lists.
Common mistakes in error handling
- A single
try/catcharound both calls. The user is told the save failed when only the reload failed. - Reading only
error.message. For Apex errors the text is usually inerror.body.message, so the user seesundefinedor a generic string. - Throwing a plain exception from Apex. The browser gets a generic message. Use
AuraHandledExceptionwithsetMessagewhen the user needs the reason. - No
finallyfor the busy flag. An exception path leavesisSavingtrue and the save button stays disabled. - Swallowing the error with an empty
catch. The refresh appears to work, but a failure is invisible. - Retrying the save automatically after a refresh failure. The save already succeeded. A retry can duplicate side effects for non-idempotent methods. Retry only the refresh.
Exercise
A user clicks Save. updateEmail succeeds, but refreshApex rejects because of a network error. With one try/catch around both calls, what does the user see, and what is wrong with it? How do you fix it?
Show answer
The user sees a message such as "Could not save", although the email is already updated in the database, and the list still shows the old value. The message is wrong and may lead the user to save again. Split the work into two try/catch blocks. Return from the first block's catch on a save failure. In the second block's catch, report that the change was saved but the list could not be reloaded, and offer a retry of the refresh only.
Exercise
Your Apex method throws a DmlException for a validation rule, but the component shows only a generic "unexpected error" message. Which change on the Apex side makes the rule's message reach the user, and where in the rejected error object does the JavaScript read it?
Show answer
Catch the DmlException in Apex and rethrow an AuraHandledException, calling setMessage with the text from getDmlMessage(0). In JavaScript, read the text from error.body.message, or use a helper like reduceErrors that also handles array bodies and plain Error objects.