Handle Component Errors

The errorCallback() is unique to Lightning Web Components. Implement it to create an error boundary component that captures errors in all the descendent components in its tree. It captures errors that occur in the descendant's lifecycle hooks or during an event handler declared in an HTML template. errorCallback() catches errors that occurs in the descendant components but not itself. You can code the error boundary component to log stack information and render an alternative view to tell users what happened and what to do next.

LWC Error Handling Best Practices

You can create an error boundary component and reuse it throughout an app. It’s up to you where to define those error boundaries. You can wrap the entire app, or every individual component. Most likely, your architecture falls somewhere in between. Think about where you’d like to tell users that something went wrong.

The error-view component displays the error returned by errorCallback(). Otherwise, it displays the healthy-view component. By wrapping your component inside the boundary component, any unhandled errors are still caught by the boundary component and displayed by error-view. When an error is thrown, healthy-view is unmounted and removed from the DOM.

The error argument is a JavaScript native error object, and the stack argument is a string.

You don’t have to use lwc:[if|elseif|else] in a template. For example, let’s say you define a single component template. If this component throws an error, the framework calls errorCallback and unmounts the component during rerender, which removes the component from the DOM.

Errors from programmatically assigned event handlers are not caught by errorCallback(), such as by using addEventHandler to your element.

See Also