Sub topic 10
Handling errors from reads and updates
This chapter assumes you can write a Lightning web component, use @wire with getRecord, and use async/await. Reads and updates fail in different ways, so each needs its own error handling.
Where errors appear
A wired getRecord does not throw. It reports failure in the result, as error instead of data. An imperative call such as updateRecord returns a promise that rejects, so you catch the failure with try/catch.
| Operation | How it reports failure | Where you handle it |
|---|---|---|
| `@wire(getRecord)` to a property | `error` property on the result | Template or getter |
| `@wire(getRecord)` to a function | `error` in the object passed to the function | Inside the function |
| `updateRecord` | Rejected promise | `catch` block |
The shape of an error
Both kinds of failure give you an error object. Its body property usually holds the server's description. For a single failure, body.message is the text to show. Some failures, such as validation errors on an update, put details in body.output.errors and body.output.fieldErrors. Network problems may have no body at all, so check before you read it.
Handling read errors
When the wire is assigned to a property, the template can test account.error. This is the pattern from the earlier chapter.
<template>
<template lwc:if={account.data}>
<p>Name: {name}</p>
</template>
<template lwc:if={account.error}>
<p>{errorMessage}</p>
</template>
</template>Compute the message in a getter, so the template stays simple. The getter below returns a fallback when the error has no body.
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class AccountReader extends LightningElement {
@api recordId;
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] })
account;
get name() {
return getFieldValue(this.account.data, NAME_FIELD);
}
get errorMessage() {
const error = this.account.error;
if (!error) {
return undefined;
}
return (error.body && error.body.message) || 'Unknown error';
}
}A wire can move from error back to data. If recordId changes and the new request succeeds, error is cleared and data is set. When you use a function wire, clear the stale value yourself, as the earlier function example did by setting errorMessage to undefined on success.
Handling update errors
Wrap updateRecord in try/catch and show the failure to the user. Common causes are a missing required field, a validation rule, no edit access, and a record changed by someone else.
import { LightningElement, api } from 'lwc';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import ID_FIELD from '@salesforce/schema/Account.Id';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class AccountSafeRename extends LightningElement {
@api recordId;
newName = '';
isSaving = false;
handleChange(event) {
this.newName = event.target.value;
}
async handleSave() {
this.isSaving = true;
const fields = {
[ID_FIELD.fieldApiName]: this.recordId,
[NAME_FIELD.fieldApiName]: this.newName
};
try {
await updateRecord({ fields });
this.toast('Success', 'Account updated', 'success');
} catch (error) {
this.toast('Error updating record', this.reduceError(error), 'error');
} finally {
this.isSaving = false;
}
}
reduceError(error) {
const body = error && error.body;
if (body && body.output && body.output.errors && body.output.errors.length) {
return body.output.errors.map((e) => e.message).join(', ');
}
return (body && body.message) || 'Unknown error';
}
toast(title, message, variant) {
this.dispatchEvent(new ShowToastEvent({ title, message, variant }));
}
}The finally block runs on both outcomes, so the saving flag is always reset. You can bind isSaving to a button's disabled attribute to prevent double submits.
Common mistakes
- Reading
this.account.datawithout checking forerror, which leaves the user with a blank component. - Awaiting
updateRecordwithouttry/catch, which produces an unhandled promise rejection. - Leaving an old error message on screen after a later success.
- Showing the raw error object to users instead of a message.
Exercise
A wired getRecord is assigned to a property named contact. The record cannot be loaded because the user lacks access. Where do you find the failure, and how does that differ from a failed updateRecord call?
Show answer
The failure appears as contact.error, and contact.data is not set. The wire does not throw. A failed updateRecord returns a rejected promise, so you must catch it with try/catch around the await.
Exercise
Why does the update example use a finally block for isSaving = false?
Show answer
finally runs whether the save succeeds or throws, so the flag is reset in both cases. Setting it only in try would leave the button disabled after a failure.