Sub topic 13
Showing row and table errors
This chapter assumes you can already render a lightning-datatable with a key-field, load its data from Apex, and save inline edits through the onsave handler, all covered earlier in this tutorial. Here you will report save failures inside the table instead of showing a generic toast.
Two kinds of error, two places to show them
A datatable can show two separate kinds of problem.
- Load errors happen before any rows exist, for example when the wired Apex method throws. The table has nothing to attach the message to, so you show it next to the table with your own markup.
- Save errors happen after the user edits cells and clicks Save. These belong inside the table, because the user needs to see which row and which cell failed.
The errors attribute handles the second kind. It does not display Apex load failures.
The shape of the errors attribute
The errors attribute takes one object with up to two properties.
| Property | Purpose | Keyed by |
|---|---|---|
| `rows` | Errors for individual rows | The value of the row's `key-field` |
| `table` | One error for the whole table | Not keyed |
Each entry, whether a row entry or the table entry, has the same fields.
| Field | Type | Meaning |
|---|---|---|
| `title` | String | Short heading for the error |
| `messages` | Array of strings | The detailed messages, one per line |
| `fieldNames` | Array of strings | Row entries only. The `fieldName` values of the columns whose cells should be highlighted |
Here is a literal example for a table whose key-field is Id.
errors = {
rows: {
'003000000000001AAA': {
title: 'We found 2 errors.',
messages: ['Enter a valid phone number.', 'Enter a valid email address.'],
fieldNames: ['Phone', 'Email']
}
},
table: {
title: 'Your changes could not be saved.',
messages: ['Fix the highlighted rows and try again.']
}
};With this value, the row whose Id is 003000000000001AAA gets an error indicator that opens a popover with the title and messages. The Phone and Email cells in that row are highlighted. The table error appears in the table's footer area, next to the Save and Cancel buttons that inline editing shows while there are draft values.
Two details cause most bugs.
- The keys under
rowsmust match thekey-fieldvalue of the row exactly. If your key field isId, use the record Id. A mismatched key means no error is shown, and the table does not warn you. fieldNamesholds columnfieldNamevalues such asPhone, not column labels such asMobile phone.
The save flow
The save handler from the inline editing chapter used Promise.all. That version has a weakness for error display. Promise.all rejects on the first failure and you lose track of which other rows succeeded. For error reporting, use Promise.allSettled, which gives you one result per row, in the same order as the drafts.
Turning a failed update into a row error
updateRecord rejects with an error object. For validation and field-level failures, the useful details sit under body.output.
body.output.fieldErrorsis an object whose keys are field API names. Each value is an array of objects with amessageproperty.body.output.errorsis an array of record-level errors, each with amessage.body.messageis a fallback summary. Some errors, such as network failures, carry only this.
The helper below flattens all three into the row error shape.
function toRowError(error) {
const body = error?.body ?? {};
const output = body.output ?? {};
const fieldErrors = output.fieldErrors ?? {};
const fieldNames = Object.keys(fieldErrors);
const messages = [
...fieldNames.flatMap((name) => fieldErrors[name].map((item) => item.message)),
...(output.errors ?? []).map((item) => item.message)
];
if (messages.length === 0) {
messages.push(body.message ?? 'An unknown error occurred.');
}
return {
title: messages.length === 1 ? 'We found 1 error.' : `We found ${messages.length} errors.`,
messages,
fieldNames
};
}A field-level failure fills fieldNames, so the matching cells are highlighted. A record-level failure, such as a validation rule that is not tied to a field, leaves fieldNames empty. The row still gets its error indicator, but no single cell is marked.
The complete component
This version makes Email and Phone editable and wires the save and cancel events. The Apex class is the ContactController from earlier in the tutorial.
import { LightningElement, wire } from 'lwc';
import { updateRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Email', fieldName: 'Email', type: 'email', editable: true },
{ label: 'Phone', fieldName: 'Phone', type: 'phone', editable: true }
];
function toRowError(error) {
const body = error?.body ?? {};
const output = body.output ?? {};
const fieldErrors = output.fieldErrors ?? {};
const fieldNames = Object.keys(fieldErrors);
const messages = [
...fieldNames.flatMap((name) => fieldErrors[name].map((item) => item.message)),
...(output.errors ?? []).map((item) => item.message)
];
if (messages.length === 0) {
messages.push(body.message ?? 'An unknown error occurred.');
}
return {
title: messages.length === 1 ? 'We found 1 error.' : `We found ${messages.length} errors.`,
messages,
fieldNames
};
}
export default class ContactErrorsTable extends LightningElement {
columns = COLUMNS;
data = [];
loadError;
wiredResult;
draftValues = [];
errors = {};
@wire(getContacts)
wiredContacts(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.data = data;
this.loadError = undefined;
} else if (error) {
this.loadError = error;
this.data = [];
}
}
get loadErrorMessage() {
return this.loadError?.body?.message ?? 'The contacts could not be loaded.';
}
async handleSave(event) {
const drafts = event.detail.draftValues;
const results = await Promise.allSettled(
drafts.map((draft) => updateRecord({ fields: { ...draft } }))
);
const rows = {};
const failedDrafts = [];
results.forEach((result, index) => {
if (result.status === 'rejected') {
rows[drafts[index].Id] = toRowError(result.reason);
failedDrafts.push(drafts[index]);
}
});
if (failedDrafts.length < drafts.length) {
await refreshApex(this.wiredResult);
}
if (failedDrafts.length === 0) {
this.errors = {};
this.draftValues = [];
return;
}
this.errors = {
rows,
table: {
title: 'Some changes could not be saved.',
messages: [`${failedDrafts.length} of ${drafts.length} rows failed. Fix them and save again.`]
}
};
this.draftValues = failedDrafts;
}
handleCancel() {
this.errors = {};
this.draftValues = [];
}
}<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<template lwc:if={loadError}>
<p class="slds-p-around_medium slds-text-color_error">{loadErrorMessage}</p>
</template>
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
draft-values={draftValues}
errors={errors}
onsave={handleSave}
oncancel={handleCancel}
hide-checkbox-column>
</lightning-datatable>
</lightning-card>
</template>Some points about this design:
- When some rows save and others fail, the handler refreshes the data and keeps only the failed drafts. The successful rows show their new values, and the failed rows keep the user's edits, so the user can correct them without retyping.
handleCancelclearserrorsalong with the drafts. Without that, old error indicators stay on rows the user has already abandoned.- The load error uses plain markup. The
errorsattribute is not the place for it.
Common mistakes
- Row key mismatch. Using an index, or a key from a different field, shows nothing. Use the same value the table uses for
key-field. - Mutating in place. As the warning above says, assign a new object.
- Leaving stale errors. After a fully successful save, set
errors = {}. An old error object stays visible otherwise. - Trusting only the client. The table only displays what you give it. Validation rules and required fields still run on the server, so the error has to come back from the save call to reach the table.
Exercise
A user edits the Phone cell on two rows and clicks Save. One update fails a validation rule on Phone, and the other succeeds. Which values should the handler assign to errors and draftValues, and why use Promise.allSettled instead of Promise.all?
Show answer
errors.rows should contain one entry, keyed by the failed row's Id, with fieldNames: ['Phone'] and the validation message in messages. You can also set an errors.table entry that summarizes the failure. draftValues should contain only the failed row's draft, so the successful row leaves the edit state and the user keeps the failed edit to correct it. Promise.allSettled returns one result for every update in draft order, so the handler can tell which rows failed. Promise.all rejects on the first failure and gives no per-row outcome.
Exercise
You set this.errors.rows[recordId] = { title: 'Bad value', messages: ['Fix it'], fieldNames: ['Email'] } and nothing changes in the table. What is wrong and how do you fix it?
Show answer
The code changes a property of the existing object, so the component never assigns a new value to errors and the table is not updated. Build a new object, for example this.errors = { ...this.errors, rows: { ...this.errors.rows, [recordId]: { title: 'Bad value', messages: ['Fix it'], fieldNames: ['Email'] } } };. Also check that recordId equals the row's key-field value.