Sub topic 8
Handling and displaying errors in the component
This chapter assumes you can already call an Apex method imperatively with async/await. It also assumes your controller throws AuraHandledException, as covered in the previous chapter. Here you will turn a rejected Promise into a message the user can read.
What a rejected call gives you
When an imperative call fails, the Promise rejects with an error object. Its shape depends on the cause:
| Cause | Where the message is |
|---|---|
| `AuraHandledException` thrown in Apex | `error.body.message` |
| Unhandled Apex exception | `error.body.message`, usually a generic text |
| Some platform errors | `error.body` is an array of objects, each with a `message` |
| Network failure | `error.message`, with no `body` |
Reading only error.body.message breaks on the last two rows. A small helper that handles every shape keeps your components short.
A reusable error helper
Create a service module named errorUtils. It exports one function that turns any error into an array of strings.
// force-app/main/default/lwc/errorUtils/errorUtils.js
export function reduceErrors(errors) {
if (!Array.isArray(errors)) {
errors = [errors];
}
return errors
.filter((error) => !!error)
.map((error) => {
if (Array.isArray(error.body)) {
return error.body.map((e) => e.message);
}
if (typeof error.body?.message === 'string') {
return error.body.message;
}
if (typeof error.message === 'string') {
return error.message;
}
return error.statusText;
})
.reduce((prev, curr) => prev.concat(curr), [])
.filter((message) => !!message);
}Using the helper in the component
The catch block clears stale data, stores the messages, and can also raise a toast. The finally block always ends the loading state.
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { reduceErrors } from 'c/errorUtils';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
export default class ContactSearch extends LightningElement {
searchTerm = '';
contacts = [];
errorMessages = [];
isLoading = false;
get hasErrors() {
return this.errorMessages.length > 0;
}
async handleSearch() {
this.isLoading = true;
this.errorMessages = [];
try {
this.contacts = await searchContacts({ searchTerm: this.searchTerm });
} catch (error) {
this.contacts = [];
this.errorMessages = reduceErrors(error);
this.dispatchEvent(
new ShowToastEvent({
title: 'Search failed',
message: this.errorMessages[0],
variant: 'error'
})
);
} finally {
this.isLoading = false;
}
}
}The template renders the list. Each message needs a key, so the example uses the message text.
<template>
<template lwc:if={hasErrors}>
<div class="slds-text-color_error" role="alert">
<template for:each={errorMessages} for:item="message">
<p key={message}>{message}</p>
</template>
</div>
</template>
</template>Choosing inline messages or toasts
- Use an inline message when the error belongs to a specific area, such as a form or a list. It stays visible until the next attempt.
- Use a toast for a short notice about an action, such as a failed save. It disappears on its own, so the user may miss it.
- Use both only when the failure matters enough to justify the extra noise.
Common mistakes
- Resetting
errorMessagesonly on success. Clear it at the start of every call, or an old error stays on screen. - Leaving old results visible after a failure. Clear
contactsin thecatchblock so the user does not read stale data as current. - Forgetting
finally. Without it, a failure can leave the spinner running.
Exercise
A user reports that after a failed search, the spinner never stops and the previous results are still shown. Which two changes to handleSearch fix this?
Show answer
Set isLoading = false in a finally block so it runs on both success and failure. Reset this.contacts = [] in the catch block so stale results are removed when the call fails.