Sub topic 8
Handling and displaying errors in the component
An imperative Apex call can fail in several ways, and each failure reaches your component as a rejected Promise. This chapter covers what the rejected value looks like, how to turn it into text a user can read, and how to show it without breaking the rest of the UI.
This chapter assumes you already know how to import an Apex method and call it with async/await inside try/catch/finally. It also assumes you know how loading state works and what AuraHandledException is for.
What a rejected call looks like
When an imperative call fails, the Promise rejects with an error object. Its shape depends on where the failure happened.
| Failure | Typical shape | Where the message is |
|---|---|---|
| `AuraHandledException` thrown in Apex | `{ body: { message }, status, statusText }` | `error.body.message` |
| Unhandled Apex exception (query, DML, null reference) | `{ body: { message, ... } }` | `error.body.message`, often less specific |
| Validation or DML failure surfaced by the platform | `{ body: { pageErrors: [], fieldErrors: {} } }` | `pageErrors[].message` and `fieldErrors[field][].message` |
| Network loss or request failure | An `Error` or object with no `body` | `error.message` or `error.statusText` |
| A bug in your own JavaScript inside `try` | A standard `Error` | `error.message` |
Because the shape varies, code that reads error.body.message directly will itself throw a TypeError for some failures. That hides the original problem. The spine example uses optional chaining for this reason:
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';That works for simple components. Once you handle field errors, arrays of errors, and strings, move the logic into one shared function.
Make the Apex message usable first
The component can only show what Apex sends. Two points matter.
First, new AuraHandledException('text') does not always put that text in getMessage(). Code that reads the message, including Apex tests, can see the generic Script-thrown exception. Calling setMessage fixes this.
Second, send only messages you are willing to show to the user. Raw exception text can expose object or field names. Catch the exceptions you expect and translate them.
public with sharing class ContactService {
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
if (String.isBlank(email)) {
throw newAuraException('Email is required.');
}
try {
Contact c = new Contact(Id = contactId, Email = email);
update as user c;
} catch (DmlException e) {
throw newAuraException(e.getDmlMessage(0));
}
}
private static AuraHandledException newAuraException(String message) {
AuraHandledException ex = new AuraHandledException(message);
ex.setMessage(message);
return ex;
}
}An expected failure, such as a blank email, belongs in an AuraHandledException with a clear message. An unexpected one, such as a NullPointerException from a bug, should not be hidden. Let it propagate so it appears in debug logs, and have the component show a generic fallback.
Normalize errors in one function
Put the parsing in a small service module so every component handles errors the same way. Create force-app/main/default/lwc/errorUtils/errorUtils.js:
export function reduceErrors(errors) {
const list = Array.isArray(errors) ? errors : [errors];
return list
.filter((error) => !!error)
.map((error) => {
if (typeof error === 'string') {
return [error];
}
const body = error.body;
if (Array.isArray(body)) {
return body.map((item) => item.message);
}
if (body) {
const messages = [];
if (typeof body.message === 'string') {
messages.push(body.message);
}
if (Array.isArray(body.pageErrors)) {
messages.push(...body.pageErrors.map((item) => item.message));
}
if (body.fieldErrors) {
Object.values(body.fieldErrors).forEach((fieldList) => {
messages.push(...fieldList.map((item) => item.message));
});
}
if (messages.length > 0) {
return messages;
}
}
if (typeof error.message === 'string') {
return [error.message];
}
return [error.statusText || 'Unknown error'];
})
.flat();
}The function accepts one error or an array and always returns an array of strings. Handling an array means the same function works for Promise.allSettled results or for errors you collect over several calls.
Use it in the component
The component keeps error state next to loading state. It clears the error at the start of each attempt and shows a toast for failures the user needs to notice.
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import updateEmail from '@salesforce/apex/ContactService.updateEmail';
import { reduceErrors } from 'c/errorUtils';
export default class ContactEmailEditor extends LightningElement {
@api contactId;
email = '';
errors = [];
isSaving = false;
handleEmailChange(event) {
this.email = event.target.value;
}
get hasErrors() {
return this.errors.length > 0;
}
get errorItems() {
return this.errors.map((text, index) => ({ key: `error-${index}`, text }));
}
async handleSave() {
this.isSaving = true;
this.errors = [];
try {
await updateEmail({ contactId: this.contactId, email: this.email });
this.dispatchEvent(
new ShowToastEvent({ title: 'Saved', message: 'Email updated.', variant: 'success' })
);
} catch (error) {
this.errors = reduceErrors(error);
} finally {
this.isSaving = false;
}
}
}The template renders the list inside an element with role="alert", so screen readers announce new errors when they appear:
<template>
<lightning-card title="Edit Email">
<div class="slds-p-around_medium">
<lightning-input label="Email" type="email" value={email} onchange={handleEmailChange}></lightning-input>
<lightning-button label="Save" onclick={handleSave} disabled={isSaving}></lightning-button>
<template lwc:if={hasErrors}>
<div role="alert" class="slds-text-color_error slds-m-top_small">
<template for:each={errorItems} for:item="item">
<p key={item.key}>{item.text}</p>
</template>
</div>
</template>
</div>
</lightning-card>
</template>Three details keep this reliable:
- Clearing
errorsbefore the call removes a stale message when the user retries. finallyresetsisSavingon both paths. If you reset it only intry, a failed call leaves the button disabled forever.- The
for:eachkey comes from a stable generated value, not from the message text, because two errors can have identical text.
Inline message or toast
Choose by how the user should react.
| Situation | Better choice |
|---|---|
| Failure is tied to the data the user is editing and they must fix it | Inline message next to the form |
| Action finished or failed in the background and no form is open | Toast |
| Failure blocks the whole component (no data can load) | Inline message in place of the content |
| Success confirmation | Toast |
Toasts disappear after a few seconds. For an error the user has to act on, use an inline message so it stays visible.
Common mistakes
- Reading
error.body.messagewith no guard. A network failure has nobody, so the handler throws a second error insidecatch. - Showing
JSON.stringify(error)to users. It leaks internal details and reads badly. Log the full object withconsole.errorduring development and show the reduced text. - Forgetting the generic Apex message. If users see
Script-thrown exception, the Apex side did not callsetMessage. - Catching in Apex and returning a status string. The component then needs two error paths. Throw an
AuraHandledExceptionand let the Promise reject. - Leaving
isLoadingtrue. This happens whenever the reset is not infinally.
Test the error path
The normalizer is a pure function, so it is the cheapest piece to test. Create errorUtils/__tests__/errorUtils.test.js:
import { reduceErrors } from '../errorUtils';
describe('reduceErrors', () => {
it('reads body.message from an AuraHandledException', () => {
const error = { body: { message: 'Email is required.' }, status: 400 };
expect(reduceErrors(error)).toEqual(['Email is required.']);
});
it('collects page and field errors', () => {
const error = {
body: {
pageErrors: [{ message: 'Page problem' }],
fieldErrors: { Email: [{ message: 'Invalid email' }] }
}
};
expect(reduceErrors(error)).toEqual(['Page problem', 'Invalid email']);
});
it('falls back to error.message when there is no body', () => {
expect(reduceErrors(new Error('Network down'))).toEqual(['Network down']);
});
it('returns an unknown-error message for an empty object', () => {
expect(reduceErrors({})).toEqual(['Unknown error']);
});
});In a component test, make the mocked Apex method fail with searchContacts.mockRejectedValue({ body: { message: 'Boom' } }). Then wait for promises to flush and assert that the rendered text contains Boom. This covers the same path a real failure takes.
Exercise
A user clicks Save while offline. The component shows a stopped spinner and no message, and the browser console shows TypeError: Cannot read properties of undefined (reading 'message') from inside the catch block. What is the cause, and what two changes fix it?
Show answer
The catch block reads error.body.message, but a network failure has no body, so the handler throws its own error before it can set any state. Fix it by reading the message defensively, for example with error?.body?.message || error?.message, or by calling a shared reduceErrors function. Also make sure the state the template renders (such as errors) is assigned inside catch, and that isLoading is reset in finally.
Exercise
Your Apex method throws new AuraHandledException('Email is required.'), but an Apex unit test that catches the exception and reads e.getMessage() gets Script-thrown exception. How do you make the message available, and why is this worth doing even though the LWC often shows the text correctly?
Show answer
Create the exception, call ex.setMessage('Email is required.'), then throw it. Without setMessage, getMessage() can return the generic text, so tests and any server-side code that reads the message see the wrong value. Setting it explicitly makes the behavior consistent everywhere.
Exercise
A form shows the same error twice in a list, and LWC logs a duplicate key warning. The template uses key={message} inside for:each. What should the key be instead?
Show answer
Use a stable unique value, such as an index-based id generated when the errors are stored (for example error-0, error-1), not the message text. Two errors can have identical text, so the text is not unique.