Error Boundary

Utility

React error boundary with fallback UI.

Preview

This content is wrapped in an ErrorBoundary. If it throws, the fallback UI is shown.

Usage

example.jsx
import { ErrorBoundary } from "@/components/ui/error-boundary";

export default function Example() {
  return <ErrorBoundary />;
}

Source Code

Copy this file into components/ui/error-boundary.jsx in your project.

error-boundary.jsx
"use client";

import { Component } from "react";

class ErrorBoundary extends Component {
  constructor(props) { super(props); this.state = { hasError: false, error: null }; }
  static getDerivedStateFromError(error) { return { hasError: true, error }; }
  componentDidCatch(error, info) { this.props.onError?.(error, info); }
  render() {
    if (this.state.hasError) {
      if (this.props.fallback) return this.props.fallback;
      return (
        <div className="rounded-lg border border-destructive/50 bg-destructive/10 p-6 text-center">
          <h3 className="font-semibold text-destructive">Something went wrong</h3>
          <p className="mt-1 text-sm text-muted-foreground">{this.state.error?.message}</p>
          <button onClick={() => this.setState({ hasError: false, error: null })}
            className="mt-3 rounded-md border px-3 py-1.5 text-sm hover:bg-accent"
          >Try Again</button>
        </div>
      );
    }
    return this.props.children;
  }
}

export { ErrorBoundary };

Quick Install

Make sure you have the cn() utility set up. It requires clsx and tailwind-merge.

npm install clsx tailwind-merge