# Handle Component Errors

The `errorCallback()` hook 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. Like a JavaScript `catch{}` block, `errorCallback()` captures errors that occur in lifecycle hooks or during an event handler declared in an HTML template. 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.

::video{src="https://youtube.com/embed/_sdRQJuAeys" title="LWC Error Handling Best Practices" type="youtube"}

After you create an error boundary component, you can 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.

```html
<!-- boundary.html -->
<template>
  <template lwc:if={error}>
    <error-view error={error} info={stack}></error-view>
  </template>
  <template lwc:else>
    <healthy-view></healthy-view>
  </template>
</template>
```

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.

```javascript
// boundary.js
import { LightningElement } from "lwc";
export default class Boundary extends LightningElement {
  error;
  stack;
  errorCallback(error, stack) {
    this.error = error;
  }
}
```

:::tip
To access the host element, use `this`. To access elements in the component’s template, use `this.template`.
:::

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.

```html
<!-- boundary.html -->
<template>
  <my-one-and-only-view></my-one-and-only-view>
</template>
```

Errors from programmatically assigned event handlers are not caught by `errorCallback()`. If you provide an event handler on an element such as for a button's `onclick` event, `errorCallback()` is called when the component encounters an error. However, if you assign the handler to your element via JavaScript such as by using `addEventHandler`, `errorCallback()` isn't called when the component encounters an error.

**See Also**

- [Lifecycle Flow](/docs/platform/lwc/guide/create-lifecycle-hooks.md)
