Sub topic 7
Handling and displaying errors
This chapter assumes you can already wire an imported Apex method to a property, read data and error from it, and use reactive parameters. Here you will learn what a wire error looks like, how to throw useful errors from Apex, how to turn any error into text, and how to show it in a template.
What a wire gives you when something fails
A wired Apex method provisions an object with two fields, data and error. Exactly one of them is set after the call finishes. Before the first response, both are undefined.
| State | `data` | `error` |
|---|---|---|
| Loading, nothing returned yet | `undefined` | `undefined` |
| Success | the returned value | `undefined` |
| Failure | `undefined` | an error object |
Two details cause most bugs:
- A failed call clears
data. If a reactive parameter changes and the new call fails, the old rows disappear. They don't stay on screen next to the error. - A successful call that returns an empty list sets
datato[]. An empty list is not an error, and it is not the loading state. Your template should treat all three differently.
The shape of an error
When Apex throws, the wire adapter gives you an object that looks like the one the Aura framework produces. The fields you will use are:
error.body.message: the message from the Apex exception.error.status: an HTTP-style code, such as500.error.statusText: a short phrase such asInternal Server Error.error.message: present on JavaScript errors and some client-side failures, such as a lost connection. These errors may have nobodyat all.
Because the shape varies, reading error.body.message directly can itself throw a TypeError when body is missing. The component in the topic's earlier example guards with error.body ? error.body.message : error.message. That works, but you will repeat it in every component, so a shared helper is better. Some Lightning Data Service adapters also return body as an array of objects, each with its own message. A helper should cover that case too.
Throw errors from Apex that the client can read
Messages from ordinary exceptions often don't reach the client in a readable form. Depending on the exception type, you may see a generic text such as Script-thrown exception. To control the message, catch the exception in Apex and rethrow an AuraHandledException.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
if (accountId == null) {
throw buildError('An account Id is required.');
}
try {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
} catch (QueryException e) {
// Thrown, for example, when the user lacks access to a field
throw buildError('You do not have access to read these contacts.');
}
}
private static AuraHandledException buildError(String message) {
AuraHandledException ex = new AuraHandledException(message);
// Without setMessage, ex.getMessage() returns "Script-thrown exception"
// in Apex tests, and some contexts read that value instead of the text.
ex.setMessage(message);
return ex;
}
}Three points about this code:
WITH USER_MODEmakes the query fail with aQueryExceptionwhen the user can't read an object or field. Catching it lets you give a clear message. Without the catch, the user would see the raw platform text.- Write user-facing messages deliberately. Don't pass
e.getMessage()straight through, because it can reveal field names, record Ids, or other internals the user shouldn't see. Log the details on the server if you need them. - A cacheable method can't perform DML. If you try, the call fails. The error appears in
errorlike any other, so you will see it during development.
Reduce any error to a list of messages
Put the extraction logic in one place. Many teams place it in a small utility module that every component imports.
// force-app/main/default/lwc/errorUtils/errorUtils.js
export function reduceErrors(error) {
if (!error) {
return [];
}
const errors = Array.isArray(error) ? error : [error];
return errors
.filter((e) => !!e)
.map((e) => {
if (Array.isArray(e.body)) {
return e.body.map((item) => item.message);
}
if (e.body && typeof e.body.message === 'string') {
return e.body.message;
}
if (typeof e.message === 'string') {
return e.message;
}
return e.statusText;
})
.flat()
.filter((message) => !!message);
}The helper returns an array of strings and never throws. If it can't find any text, the array is empty, so the caller should supply a fallback such as "Unknown error".
Other components import it by its folder name:
import { reduceErrors } from 'c/errorUtils';Wire to a function and keep error state in fields
Wiring to a property, as in contacts.error, is the shortest form. Wiring to a function lets you convert the error to text once, store it in a field, and keep the template simple. The following component uses the helper and tracks a loading state.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import { reduceErrors } from 'c/errorUtils';
export default class ContactListErrors extends LightningElement {
@api recordId;
rows;
errorMessages = [];
isLoading = true;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts({ data, error }) {
if (data) {
this.rows = data;
this.errorMessages = [];
this.isLoading = false;
} else if (error) {
this.rows = undefined;
this.errorMessages = reduceErrors(error);
if (this.errorMessages.length === 0) {
this.errorMessages = ['Unknown error'];
}
this.isLoading = false;
}
}
get hasError() {
return this.errorMessages.length > 0;
}
get isEmpty() {
return Array.isArray(this.rows) && this.rows.length === 0;
}
get hasRows() {
return Array.isArray(this.rows) && this.rows.length > 0;
}
}Both branches reset the other field. Without that reset, a success after a failure would leave the old error on screen. The isLoading flag starts as true. Note that it is never set back to true when recordId changes. If you need a spinner on every reload, you would have to set it elsewhere, for example in a setter on recordId.
The template handles four states: loading, error, empty, and rows.
<template>
<template lwc:if={isLoading}>
<lightning-spinner alternative-text="Loading contacts"></lightning-spinner>
</template>
<template lwc:elseif={hasError}>
<div class="slds-text-color_error" role="alert">
<template for:each={errorMessages} for:item="message">
<p key={message}>{message}</p>
</template>
</div>
</template>
<template lwc:elseif={isEmpty}>
<p>This account has no contacts.</p>
</template>
<template lwc:elseif={hasRows}>
<ul>
<template for:each={rows} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
</template>Setting role="alert" makes screen readers announce the message when it appears. The key on each message must be unique among its siblings. If two messages could be identical, build a key from the message and its index in the helper.
Errors that the wire never sees
The error field reports failures of the Apex call. It does not cover everything that can go wrong:
- A reactive parameter that is
undefinedmeans the wire does not call Apex at all. You get neitherdatanorerror, so the component looks like it is loading forever. IfrecordIdcan be missing, handle that case with a template check or a getter. - A JavaScript error thrown inside your wired function is not routed to
error. It surfaces as an uncaught exception in the console. Keep the function small and defensive. - With cached data, a call can return stale data without any error. The next chapters on caching and
refreshApexcover this.
For imperative calls, which you will meet in a later chapter, errors arrive in a catch block instead. The same helper works there, because the error object has the same shape.
Show errors in a reusable way
When many components need the same display, wrap it in a small child component that takes the messages as an @api property:
import { LightningElement, api } from 'lwc';
export default class ErrorPanel extends LightningElement {
@api messages = [];
get hasMessages() {
return Array.isArray(this.messages) && this.messages.length > 0;
}
}Parents then pass errorMessages and stay free of display markup. For transient problems, such as a failed button click, a toast from lightning/platformShowToastEvent suits better than an inline panel. For a failed initial load, an inline message is better because the user can still see it after the toast disappears.
Common mistakes
- Reading
error.body.messagewithout checking thatbodyexists. - Forgetting
setMessageonAuraHandledException, which makes tests and some callers seeScript-thrown exception. - Leaking internal details by returning
e.getMessage()from aQueryExceptionorDmlException. - Treating an empty list as an error, or the loading state as an empty list.
- Leaving the previous error visible after a successful reload.
Exercise
A wired component shows "This account has no contacts." for a few moments on every page load, and then the list appears. What is most likely wrong, and how do you fix it?
Show answer
The template treats the loading state like an empty result, probably by testing !contacts.data or by treating undefined the same as []. Before the first response both data and error are undefined, so the empty message must only show when data is an array with length 0. Add an explicit loading state, as in isLoading, and compute isEmpty with Array.isArray(this.rows) && this.rows.length === 0.
Exercise
Your Apex method throws new AuraHandledException('No access') but a Jest or Apex test shows getMessage() returning "Script-thrown exception". What do you add, and why?
Show answer
Call ex.setMessage('No access') on the exception before throwing it. The constructor message is what the client sees in some paths, but getMessage() returns the generic text until setMessage is called.