Sub topic 7
Handling and displaying errors
This chapter assumes you can write a basic LWC, know how @wire provisions data to a property or function, and can read simple Apex. Here you will learn what an error from a wired Apex method looks like, how to pull a readable message out of it, and how to show it in the template.
What an Apex error looks like
When a wired Apex method fails, the wire service gives your component an error value in place of data. A wire sets only one of the two at a time. If the Apex method throws an exception, for example a QueryException or an AuraHandledException, error is an object with a body property. The readable text is in error.body.message.
Errors that never reach Apex have a different shape. A network failure or a client-side problem gives you a standard JavaScript Error, where the text is in error.message and there is no body. Your code has to handle both shapes.
The diagram below shows the decision your handler makes.
Showing the error from a property wire
When you wire to a property, the property holds an object with data and error. The template can test each one. This is the markup from the property-wiring example, which uses lwc:if and lwc:elseif.
<template>
<template lwc:if={contacts.data}>
<ul>
<template for:each={contacts.data} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
<template lwc:elseif={contacts.error}>
<p>Could not load contacts.</p>
</template>
</template>This tells the user something went wrong, but not why. It also hides the cause from you while you develop. To show the real message, you need to compute it in JavaScript, because templates cannot run expressions such as contacts.error.body.message. Template expressions can only read properties, and the body property may not exist.
Extracting the message in a function wire
Wiring to a function gives you a place to normalize the error once and store a plain string. The handler below stores the message in errorMessage and clears the old data.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactListFn extends LightningElement {
@api recordId;
rows;
errorMessage;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts({ data, error }) {
if (data) {
this.rows = data;
this.errorMessage = undefined;
} else if (error) {
this.rows = undefined;
this.errorMessage = error.body ? error.body.message : error.message;
}
}
}The ternary error.body ? error.body.message : error.message covers both error shapes. Each branch also clears the other field. Without that, a refetch that fails after an earlier success would show stale rows next to the new error message.
Common errors
- Reading
error.body.messagewithout a check. A client-side error has nobody, so this line throws aTypeErrorinside your error handler. - Showing the raw error object.
{error}in a template prints[object Object]. Display a string. - Leaking details to users. Exception messages can include SOQL or field names. Show a friendly message to users and log the detail.
- Leaving stale state. Reset
dataanderrortogether, as the handler above does. - Expecting a message from an unhandled Apex exception. A plain exception reaches the client with a generic text, such as "Script-thrown exception". Throw an
AuraHandledExceptionfrom Apex when you want a specific, safe message to reach the component.
Setting the message in Apex
An AuraHandledException lets you decide the text the component receives. Call setMessage so the message you set is what appears in error.body.message.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
try {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
} catch (QueryException e) {
AuraHandledException ex = new AuraHandledException('Contacts could not be read.');
ex.setMessage('Contacts could not be read.');
throw ex;
}
}
}Exercise
A wired function handler runs this.errorMessage = error.body.message;. A user goes offline and the component throws a TypeError. What is the cause, and how do you fix it?
Show answer
A network failure produces a standard JavaScript Error with no body property, so error.body.message reads a property of undefined. Use error.body ? error.body.message : error.message so both error shapes are handled.
Exercise
Why does the template example show only a fixed "Could not load contacts." text, and how would you display the real reason?
Show answer
Template expressions only read properties, and error.body may not exist, so the template cannot safely reach the message. Compute a string such as errorMessage in JavaScript, in a function wire or a getter, and bind that string in the template.