How do error boundaries and errorCallback methods work for handling component exceptions in LWC?
Answer
Basics: Without a boundary, an exception in one child can blank out a large part of the page. A boundary component wraps risky children, catches the error, and swaps in a friendly message.
How it works:
- Define
errorCallback(error, stack)in a wrapper (ancestor) component. - When any descendant throws in a covered phase, the framework calls it with the error and a string describing the component stack.
- Set a state field such as
this.error = errorto switch the template to fallback UI, and log details. - The wrapper template shows
<slot>normally, or a fallback whenerroris set.
Advanced / deep dive: The boundary does not catch errors thrown in its own code, nor errors in asynchronous operations such as promises, setTimeout, or async handlers; those need try/catch or .catch. Errors in Apex calls surface as rejected promises, so handle them where made. Typical design: one generic errorBoundary component that wraps a page region, logs through an Apex logger or platform event (for example to a custom log object or a framework such as Nebula Logger), and offers a retry button that clears the error to re-render the children. Because rendering removes the failed subtree, retry creates fresh instances. Boundaries should be placed around independent regions so one failure does not hide others. In production the error message from some failures is generic, so include context in the log. For Aura, use aura:handler event="aura:systemError" or try/catch in controllers.
Code / config example:
import { } ;
{
error;
() {
. = error;
.(, error?., stack);
}
() { . = ; }
}