Sub topic 10
Handling errors from reads and updates
This chapter covers what goes wrong when a Lightning web component reads a record with getRecord or saves one with updateRecord, and how to show those failures to the user. It assumes you know JavaScript promises and async/await, the structure of a Lightning web component, and how @api recordId works on a record page. It also assumes you have seen the { data, error } result of a wire.
Two error paths
Reads and updates report errors differently, because they use different mechanisms.
getRecordis a wire adapter. It never throws. The wire service provisions a result object that contains eitherdataorerror.updateRecordis an imperative function that returns a promise. A failure rejects the promise, so you catch it withtry/catchor.catch().
Both kinds of failure give you the same error shape, so one helper can format messages for both.
The shape of an error
When a Lightning Data Service request fails, the error is a FetchResponse-style object. The useful parts are:
status: the HTTP status code, such as 404 or 400.statusText: the matching text, such asNot Found.body: the payload from the server. For a single failure it is an object with amessageand anerrorCode. For some failures, such as validation problems on a save,body.output.errorsholds a list of field-level errors, andbody.output.fieldErrorsgroups them by field.
Not every error looks like this. A network failure or a bug in your own code produces a plain JavaScript Error with a message and no body. Your formatting code must handle both.
// errorUtils.js
export function reduceErrors(errors) {
if (!Array.isArray(errors)) {
errors = [errors];
}
return errors
.filter((error) => !!error)
.map((error) => {
// Lightning Data Service and Apex errors
if (error.body) {
if (Array.isArray(error.body)) {
return error.body.map((e) => e.message);
}
if (error.body.output && error.body.output.errors && error.body.output.errors.length) {
return error.body.output.errors.map((e) => e.message);
}
if (typeof error.body.message === 'string') {
return error.body.message;
}
}
// JavaScript errors
if (typeof error.message === 'string') {
return error.message;
}
// Fallback
return error.statusText || 'Unknown error';
})
.reduce((prev, curr) => prev.concat(curr), [])
.filter((message) => !!message);
}Place this file in a shared service component, for example c/errorUtils, and import it where you need it. The function always returns an array of strings, which keeps the template simple.
Common read errors
A wire can fail for several reasons. Knowing the typical ones helps you decide what to tell the user.
| Cause | Typical status | What you see |
|---|---|---|
| The record ID does not exist or was deleted | 404 | `NOT_FOUND` in `body` |
| The user lacks read access to the record | 404 or 403 | Record appears not to exist |
| A required field in `fields` is not accessible to the user | 400 or 404 | The whole request fails |
| A field name is invalid or the ID has the wrong format | 400 | `body.message` describes the problem |
| Network loss | none | A plain `Error`, often without `body` |
The third row matters most. If you list a field under fields and the user cannot read it, the entire request fails and you get an error instead of any data. Fields listed under optionalFields are different: an inaccessible optional field is left out of the result, and the rest of the record loads. If a field's absence should not block the component, request it as optional. Chapter on fields versus optionalFields covers this choice; here the point is that the choice decides whether you see an error.
Displaying read errors
Keep the wire result on a property and let the template branch on it. This is the pattern from the earlier chapters, extended with a formatted message.
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import { reduceErrors } from 'c/errorUtils';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class AccountHeader extends LightningElement {
@api recordId;
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] })
account;
get name() {
return getFieldValue(this.account.data, NAME_FIELD);
}
get errorMessages() {
return this.account.error ? reduceErrors(this.account.error) : [];
}
}<template>
<template lwc:if={account.data}>
<h2>{name}</h2>
</template>
<template lwc:if={account.error}>
<template for:each={errorMessages} for:item="message">
<p key={message} class="slds-text-color_error">{message}</p>
</template>
</template>
</template>Two details are easy to miss:
- While the first request is in flight, both
dataanderrorareundefined. Neither branch renders, so the user sees an empty component. If that matters, add a spinner for the case where neither is set. - A wire result is replaced on each provision. After an error, a later successful provision (for example when
recordIdchanges) gives youdataand clearserror. Do not copy an error into your own state and forget to clear it.
Handling errors in a function wire
When you wire to a function, the function runs for each new result and receives { data, error }. Because you own the state, you must reset the opposite value yourself, or a stale error stays on screen after a later success.
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import { reduceErrors } from 'c/errorUtils';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class AccountNameStatus extends LightningElement {
@api recordId;
name;
errorMessages = [];
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] })
wiredAccount({ data, error }) {
if (data) {
this.name = getFieldValue(data, NAME_FIELD);
this.errorMessages = [];
} else if (error) {
this.name = undefined;
this.errorMessages = reduceErrors(error);
}
}
}Each branch sets both properties. That is the part to check in code review.
Handling errors from updateRecord
updateRecord rejects its promise when the save fails. Reasons include:
- A validation rule, required field, or trigger rejects the change.
- The user lacks edit permission on the record or a field.
- The record changed on the server after the component read it, when you use optimistic concurrency checks.
- A network failure.
Wrap the call in try/catch. Show a toast for a short message, or render the messages inline when the user needs to correct input.
import { LightningElement, api } from 'lwc';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { reduceErrors } from 'c/errorUtils';
import ID_FIELD from '@salesforce/schema/Account.Id';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class AccountRenameWithErrors extends LightningElement {
@api recordId;
newName = '';
errorMessages = [];
isSaving = false;
handleChange(event) {
this.newName = event.target.value;
}
async handleSave() {
this.isSaving = true;
this.errorMessages = [];
const fields = {};
fields[ID_FIELD.fieldApiName] = this.recordId;
fields[NAME_FIELD.fieldApiName] = this.newName;
try {
await updateRecord({ fields });
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Account updated',
variant: 'success'
})
);
} catch (error) {
this.errorMessages = reduceErrors(error);
this.dispatchEvent(
new ShowToastEvent({
title: 'Error updating record',
message: this.errorMessages.join(', '),
variant: 'error'
})
);
} finally {
this.isSaving = false;
}
}
}The finally block runs on both outcomes, so the saving flag cannot stay true after a failure. Clearing errorMessages at the start of each attempt prevents an old message from lingering beside a new success.
Field-level errors
For a validation failure, error.body.output.fieldErrors is an object keyed by field API name. Each value is an array of error objects with message and errorCode. Use it when you want to attach a message to one input instead of listing everything in one place.
function getFieldErrors(error, fieldApiName) {
const fieldErrors =
error && error.body && error.body.output && error.body.output.fieldErrors;
if (!fieldErrors || !fieldErrors[fieldApiName]) {
return [];
}
return fieldErrors[fieldApiName].map((e) => e.message);
}Errors not tied to a field, such as a failing trigger or a record-level validation rule, appear in body.output.errors instead. Handle both lists, or you will drop messages.
Mistakes to avoid
- Reading
error.messageonly. LDS errors keep their text inerror.body.message. Reading the top-levelmessagegivesundefinedfor these. Use a helper that checks both. - Assuming
error.bodyexists. Code likeerror.body.messagethrows a second error when the failure is a plainError. Guard it, as the helper does. - Using
try/catcharound a wire. A wire does not throw into your code. Check theerrorproperty. - Forgetting to clear state. In a function wire or a save handler, reset the old error when a new attempt starts or succeeds.
- Showing raw errors to users. Messages such as
INVALID_CROSS_REFERENCE_KEYhelp developers. For production, log the details and show a plain message where the raw text would confuse users. - Skipping the inaccessible field case. If a user cannot read a field you listed under
fields, the whole component shows an error. Decide per field whether it is truly required.
Exercise
A component wires getRecord with fields: [NAME_FIELD, REVENUE_FIELD]. A user without access to AnnualRevenue opens the page, and the component shows only an error. What change lets the name display for that user, and why does it work?
Show answer
Move REVENUE_FIELD from fields to optionalFields. A field in fields that the user cannot read makes the whole request fail, so only error is set. A field in optionalFields that the user cannot read is left out of the result, so the request succeeds and data contains the name. The template should then handle the missing revenue value, because getFieldValue returns undefined for it.
Exercise
In an async save handler, the call await updateRecord({ fields }) fails with a validation rule error. Which property of the caught error holds the list of messages, and why does a single check of error.message miss them?
Show answer
The messages are in error.body.output.errors, and field-specific ones are in error.body.output.fieldErrors. Lightning Data Service errors store their details in body, so the top-level error.message is undefined for them. A helper such as reduceErrors checks body first and falls back to message for plain JavaScript errors.