Skip to main content

Error boundary

Examples

Check out the Usage section for details about how to design an error boundary properly, and the different configuration options we provide.

Basic example

Error boundaries are wrappers that will render a fallback component if one of its children has an error.

<ErrorBoundary>
<BadComponent/>
</ErrorBoundary>

Customization example

You can pass props to the error boundary component that will be passed to its fallback component.

<ErrorBoundary noticeStyle="card" showErrorMessage>
<BadComponent/>
</ErrorBoundary>

Simple custom fallback example

You can define your own fallback component to render when an error occurs.

function AlternateFallback () {
return (
<strong>An error occurred.</strong>
)
}

...

<ErrorBoundary fallbackComponent={AlternateFallback}>
<BadComponent/>
</ErrorBoundary>

Custom fallback with error message example

An object will be passed to the fallback component that contains the JavaScript error object as one of its properties.

function AlternateFallback({error}) {
return (
<span><strong>An error occurred:</strong>&nbsp;{error.message}</span>
)
}

...

<ErrorBoundary fallbackComponent={AlternateFallback}>
<BadComponent/>
</ErrorBoundary>

Custom fallback with props example

Additional props passed to the error boundary component will be added as props for the component passed to fallbackComponent.

function MakeToast(error) {
ToastProvider.toast({
message: error.message,
autoClose: 3000,
type: "error",
});
}

function AlternateFallback({error, buttonLabel}) {
return (
<>
<ToastProvider />
<Button label={buttonLabel} onClick={(error) => MakeToast(error)}/>
</>
)
}

...

<ErrorBoundary
fallbackComponent={AlternateFallback}
buttonLabel="Click for notification"
>
<BadComponent/>
</ErrorBoundary>