Errors, Debugging and Security · Lesson 19 of 25
Error Handling in LWC: Apex Errors, Toasts and errorCallback
Users don't care that "an unexpected error occurred" – they want to know what went wrong and what to do. Good error handling in LWC means three things: catching errors where they happen, turning the platform's different error formats into one readable message, and making sure one broken child doesn't blank the whole page.
In this lesson
- try/catch/finally and throwing your own errors
- What Apex, DML and UI API errors look like
- A reusable reduceErrors helper
- Toasts and inline messages
- errorCallback: an error boundary for child components
try, catch, finally and custom errors
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
function validateDiscount(percent) {
if (typeof percent !== 'number' || Number.isNaN(percent)) throw new TypeError('Discount must be a number');
if (percent > 30) throw new ValidationError('Discount__c', 'Discounts above 30% need approval');
return percent;
}
for (const value of [10, 45, 'ten']) {
try {
console.log(`ok: ${validateDiscount(value)}%`);
} catch (e) {
if (e instanceof ValidationError) console.log(`${e.name} on ${e.field}: ${e.message}`);
else console.log(`${e.name}: ${e.message}`);
} finally {
console.log(' (checked)');
}
}
ok: 10% (checked) ValidationError on Discount__c: Discounts above 30% need approval (checked) TypeError: Discount must be a number (checked)
- Throw
Errorobjects (or subclasses), never strings – you lose the stack trace ande.message. - A custom class lets callers react differently to expected problems (a validation rule) and real bugs.
- Only catch where you can do something useful: show a message, retry, fall back. Swallowing errors with an empty
catch {}hides bugs.
The many shapes of Salesforce errors
An error from the platform isn't a plain Error. Its shape depends on where it came from:
| Source | Where the message is |
|---|---|
Apex AuraHandledException / unhandled exception | error.body.message |
| Apex DML exception | error.body.pageErrors[].message and error.body.fieldErrors |
| UI API (getRecord, updateRecord…) | error.body.message or error.body.output.errors[].message / fieldErrors |
| Several wire errors at once | an array of the above |
| Your own JavaScript | error.message |
That's why every mature codebase has a helper – often called reduceErrors – that flattens any of these into an array of strings. Put it in a shared module such as c/ldsUtils:
// ldsUtils.js
export function reduceErrors(errors) {
const list = Array.isArray(errors) ? errors : [errors];
return list
.filter((error) => !!error)
.flatMap((error) => {
const body = error.body;
if (Array.isArray(body)) return body.map((e) => e.message); // UI API read errors
if (body?.pageErrors?.length || body?.fieldErrors) { // DML errors
const page = (body.pageErrors ?? []).map((e) => e.message);
const fields = Object.values(body.fieldErrors ?? {}).flat().map((e) => e.message);
return [...page, ...fields];
}
if (body?.output?.errors?.length || body?.output?.fieldErrors) { // UI API write errors
const out = body.output;
return [...(out.errors ?? []).map((e) => e.message),
...Object.values(out.fieldErrors ?? {}).flat().map((e) => e.message)];
}
if (typeof body?.message === 'string') return [body.message]; // Apex
if (typeof error.message === 'string') return [error.message]; // JavaScript
return [error.statusText ?? 'Unknown error'];
})
.filter((message) => !!message);
}
// try it with each shape
console.log(reduceErrors({ body: { message: 'You do not have access to this account' } }));
console.log(reduceErrors({ body: { pageErrors: [{ message: 'Close date cannot be in the past' }], fieldErrors: { Amount: [{ message: 'Amount must be positive' }] } } }));
console.log(reduceErrors({ body: { output: { errors: [], fieldErrors: { Email: [{ message: 'Invalid email address' }] } } } }));
console.log(reduceErrors([new TypeError('x is undefined'), undefined, { statusText: 'Server Error' }]));
[ 'You do not have access to this account' ] [ 'Close date cannot be in the past', 'Amount must be positive' ] [ 'Invalid email address' ] [ 'x is undefined', 'Server Error' ]
Send readable messages from Apex
In Apex, catch expected problems and throw new AuraHandledException('Clear message for the user'). Unexpected system exceptions can expose internal details or arrive as a generic message, so decide deliberately what the user sees.
Showing errors: toast or inline
Use a toast for the result of an action (save failed, record deleted) and an inline message for a part of the page that couldn't load:
// opportunityCloser.js
import { LightningElement, api } from 'lwc';
import Toast from 'lightning/toast';
import closeOpportunity from '@salesforce/apex/OpportunityService.closeOpportunity';
import { reduceErrors } from 'c/ldsUtils';
export default class OpportunityCloser extends LightningElement {
@api recordId = '006A';
isSaving = false;
async handleClose() {
this.isSaving = true;
try {
await closeOpportunity({ opportunityId: this.recordId });
Toast.show({ label: 'Opportunity closed', variant: 'success' }, this);
} catch (error) {
Toast.show({ label: 'Could not close the opportunity', message: reduceErrors(error).join('; '), variant: 'error', mode: 'sticky' }, this);
} finally {
this.isSaving = false;
}
}
}
<!-- opportunityCloser.html -->
<template>
<lightning-button label="Close as won" onclick={handleClose} disabled={isSaving}></lightning-button>
</template>
[Close as won] › click “Close as won” [Close as won] toast (error): Could not close the opportunity – Close date cannot be in the past › click “Close as won” [Close as won] toast (success): Opportunity closed
(The example imports reduceErrors from the c/ldsUtils module shown above.) Error toasts use mode: 'sticky' so the user has time to read them; success toasts can disappear on their own.
errorCallback: an error boundary
If a child component throws while rendering or in a lifecycle hook, the error travels up. A parent that implements errorCallback(error, stack) catches it – like a catch block for its whole subtree – and can show a fallback instead of a broken page:
// riskyWidget.js
import { LightningElement, api } from 'lwc';
export default class RiskyWidget extends LightningElement {
@api config;
connectedCallback() {
// a bug: config is missing on this page
this.title = this.config.title.toUpperCase();
}
}
<!-- riskyWidget.html -->
<template>
<p>{title}</p>
</template>
// widgetBoundary.js
import { LightningElement } from 'lwc';
export default class WidgetBoundary extends LightningElement {
failed = false;
errorText = '';
errorCallback(error) {
this.failed = true;
this.errorText = error.message;
// in a real org, also log it: e.g. publish to a logging Apex method or event
}
}
<!-- widgetBoundary.html -->
<template>
<p>Dashboard</p>
<template lwc:if={failed}>
<p>This widget could not load. ({errorText})</p>
</template>
<template lwc:else>
<c-risky-widget></c-risky-widget>
</template>
</template>
Dashboard This widget could not load. (Cannot read properties of undefined (reading 'title'))
errorCallbackcatches errors from descendants' lifecycle hooks and rendering – not from the parent itself, and not from event handlers or async code (those need their own try/catch).- Wrap risky or third-party pieces of a page in a boundary so the rest stays usable.
Practice
Try it yourself
An Apex method throws a DML exception from a validation rule, and your toast shows "undefined". What's wrong?
Show answer
The code reads
error.body.message, but DML errors put their messages inerror.body.pageErrorsandfieldErrors. Use a helper likereduceErrorsthat understands every shape.Will
errorCallbackcatch an error thrown inside a child'shandleClick?Show answer
No. It catches errors from lifecycle hooks and rendering. Errors in event handlers and promises must be caught with try/catch in that code.
Quick check
Where is the message of an AuraHandledException?
error.body.message.
Why throw Error objects instead of strings?
They carry a name, message and stack trace.
What does errorCallback do?
Catches errors from descendant components' lifecycle hooks and rendering.
Summary
- Throw Error objects; use custom error classes for expected problems.
- Platform errors come in several shapes – flatten them with reduceErrors.
- Toasts for action results, inline messages for failed sections.
- Use errorCallback as an error boundary; try/catch handlers and async code.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.