Sub topic 10
errorCallback(): catching errors from child components
This chapter covers errorCallback(), the hook that lets a component handle errors thrown by its descendants. It assumes you know basic JavaScript classes and ES modules, how to build an LWC with an HTML template and a JavaScript class, how reactive fields and template expressions work, and how DOM events work. It also assumes you have read the earlier chapters on connectedCallback(), renderedCallback(), and the order of hooks across parent and child components.
What errorCallback() does
When a lifecycle hook in a child component throws, the error would normally unwind the whole component tree and leave the page broken. errorCallback() lets an ancestor intercept that error. A component that defines it acts as an error boundary. It catches errors from the components below it, records them, and lets its template show a fallback view.
The signature is:
errorCallback(error, stack) {
// handle the error
}erroris the JavaScriptErrorobject that was thrown.stackis a string describing the component stack. It shows which components were involved when the error occurred.
The hook runs on an ancestor. It does not run on the component that threw the error. A component cannot use its own errorCallback() to catch its own failures.
What it catches
errorCallback() catches errors thrown in a descendant's:
constructor()connectedCallback()render()renderedCallback()- template evaluation, such as a getter that the template reads and that throws
The hook is for lifecycle and rendering problems. It has limits that matter in practice:
| Situation | Caught by errorCallback()? |
|---|---|
| Error thrown in a child's `connectedCallback()` | Yes |
| Error thrown in a child's `renderedCallback()` | Yes |
| Error thrown in a child's `render()` | Yes |
| Error thrown inside the boundary component's own hooks | No |
| Error thrown in an event handler | No |
| Error inside a `setTimeout` callback or a promise rejection | No |
Event handlers, timers, and promises run outside the render cycle. Handle those errors yourself with try...catch or with .catch() on the promise.
A basic error boundary
The code below stores the error and stack. The template can then choose between the normal content and a fallback.
import { LightningElement } from 'lwc';
export default class ErrorBoundary extends LightningElement {
error;
stack;
errorCallback(error, stack) {
this.error = error;
this.stack = stack;
}
}The error and stack fields are reactive, so assigning to them schedules a re-render. In the template, branch on error:
<template>
<template lwc:if={error}>
<p>Something went wrong.</p>
<p>{error.message}</p>
</template>
<template lwc:else>
<c-child-widget></c-child-widget>
</template>
</template>When error is set, the template stops rendering c-child-widget. The failing child leaves the DOM, which also triggers its disconnectedCallback().
Hook order when an error occurs
Take a boundary component with a child that throws in connectedCallback(). The sequence is:
- The boundary's
constructor()runs. - The boundary's
connectedCallback()runs. - The boundary renders, which creates the child.
- The child's
constructor()runs. - The child's
connectedCallback()throws. - The boundary's
errorCallback()receives the error and stack. - The boundary re-renders with the fallback view.
The next diagram shows the same sequence.
Making the boundary useful
A boundary that only shows a generic message is a start. A more useful one does three things:
- It shows a fallback that matches the page, not a raw stack trace.
- It reports the error somewhere you can find it, such as a logging service or the browser console.
- It offers a way to recover, such as a retry button.
The next example does all three. It logs the error, keeps a friendly message for the template, and clears the error when the user clicks retry.
import { LightningElement } from 'lwc';
export default class SafeRegion extends LightningElement {
error;
stack;
errorCallback(error, stack) {
// eslint-disable-next-line no-console
console.error('Child component failed:', error.message, stack);
this.error = error;
this.stack = stack;
}
get message() {
return this.error ? this.error.message : '';
}
handleRetry() {
this.error = undefined;
this.stack = undefined;
}
}<template>
<template lwc:if={error}>
<div role="alert">
<p>This section could not be loaded.</p>
<p>{message}</p>
<button onclick={handleRetry}>Try again</button>
</div>
</template>
<template lwc:else>
<slot></slot>
</template>
</template>This boundary uses a <slot>, so it can wrap any content:
<template>
<c-safe-region>
<c-risky-chart></c-risky-chart>
</c-safe-region>
</template>Clearing error makes the template render the slot again. The browser creates a fresh instance of c-risky-chart, so the retry runs its constructor and connectedCallback() from the start. If the cause of the failure is still there, the child throws again and the boundary shows the fallback again.
Where to place boundaries
A boundary only protects what sits beneath it. Where you put it decides how much of the page survives a failure.
- A boundary near the top of the page gives one fallback for everything. It is simple, but a failure in a minor widget replaces the whole page.
- A boundary around each independent region keeps the rest of the page working. A broken chart does not remove the form beside it.
- Nested boundaries are allowed. The error goes to the closest ancestor that defines
errorCallback(), so an inner boundary can handle its region and an outer one catches anything else.
Wrap parts that can fail for reasons you do not control, such as components that render data from an external source or third-party components. Components that only render static markup rarely need one.
What to do inside errorCallback()
Keep the hook short and safe. It runs while the framework is recovering from a failure, so a second error here makes things worse.
- Assign the error and stack to fields so the template can react.
- Log or report the error.
- Do not call methods on the failed child. It may be in a half-built state.
- Do not throw from
errorCallback(). An error thrown here goes to the next boundary up, or becomes unhandled if none exists. - Do not do heavy work or start long network calls.
If there is no boundary above the failing component, the error is not handled by LWC and the failure surfaces to the browser or the host platform. In that case the user may see a broken region or a platform error message.
Common mistakes
- Putting
errorCallback()on the component that fails. It only receives errors from descendants. Move it to a parent. - Expecting it to catch event handler errors. Wrap handler code in
try...catch. - Forgetting the template branch. Storing the error does nothing visible unless the template reads it. Without a branch, the template can keep rendering the failing child and the error repeats.
- Reading
error.messagewhenerroris unset. Uselwc:if={error}or a getter that checks first, as in the example above. - Swallowing errors silently. If you store the error but never log it, nobody learns that something broke. Always report it.
- Showing raw stack traces to users. Log the stack and show a plain message instead.
Testing a boundary
You can test an error boundary with Jest by creating a child that throws. The stub below fails in its constructor path through connectedCallback():
import { LightningElement } from 'lwc';
export default class AlwaysFails extends LightningElement {
connectedCallback() {
throw new Error('Intentional failure');
}
}Place it inside the boundary in a test or a sandbox page, and check that the fallback appears. Make sure the page outside the boundary still renders. This confirms the boundary is in the right place and that the template branches correctly.
Exercise
A component c-parent defines errorCallback(). Its child c-child throws an error inside an onclick event handler. Does errorCallback() on c-parent run? What should you do instead?
Show answer
No. errorCallback() only catches errors thrown during the component's lifecycle and rendering, such as in the constructor, connectedCallback(), render(), and renderedCallback(). An event handler runs outside that cycle. Wrap the handler body in try...catch, and set a field in the catch block so the template can show a message.
Exercise
A boundary component stores the error in this.error inside errorCallback(), but its template always renders <c-child> without checking error. What happens, and how do you fix it?
Show answer
The child keeps rendering, so the visible result does not change and the error can occur again on the next render. Fix it by branching in the template, for example <template lwc:if={error}> for the fallback and <template lwc:else> for <c-child>, so the failing child is removed once an error is recorded.
Exercise
You want to protect a page that has a data table and a separate chart. The chart uses a third-party library that sometimes throws during renderedCallback(). Where would you place error boundaries, and why?
Show answer
Place one boundary around the chart only, and optionally an outer boundary for everything else. With a boundary around the chart, a chart failure shows a fallback in the chart's area while the data table keeps working. A single boundary around both would replace the table too.