SCALE — Build Lab
開発パターン · REACT PATTERN

エラーバウンダリー

CATEGORY開発パターン TYPEReact Pattern EFFORT30〜90分 DIFFICULTY
PRIMARY CODE
tsx
'use client';
import { Component, ReactNode, ErrorInfo } from 'react';

type Props = { children: ReactNode; fallback?: (e: Error) => ReactNode };
type State = { error: Error | null };

export class ErrorBoundary extends Component<Props, State> {
  state: State = { error: null };

  static getDerivedStateFromError(error: Error): State {
    return { error };
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    // エラー報告連携(Sentry等)
    console.error('ErrorBoundary:', error, info.componentStack);
    if (typeof window !== 'undefined' && (window as any).Sentry) {
      (window as any).Sentry.captureException(error);
    }
  }

  reset = () => this.setState({ error: null });

  render() {
    if (this.state.error) {
      if (this.props.fallback) return this.props.fallback(this.state.error);
      return (
        <div className="p-6 bg-rose-500/10 border border-rose-500/30 rounded-2xl">
          <h2 className="text-rose-300 font-semibold mb-2">エラーが発生しました</h2>
          <p className="text-sm text-zinc-400 mb-3">{this.state.error.message}</p>
          <button onClick={this.reset} className="px-3 py-1 rounded-lg bg-rose-500 text-white text-sm">
            再試行
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

// 使い方:
// <ErrorBoundary><MyComponent /></ErrorBoundary>
前提条件
Tailwind CSS v4TypeScript 5
USE CASES
  • 全アプリ

エラーバウンダリー

:LiTarget: 用途

コンポーネントエラーをキャッチしてフォールバックUIを表示。

:LiSparkle: 特徴

  • エラーキャッチ
  • フォールバック
  • エラー報告連携

:LiCode: コード(コピペ用)

'use client';
import { Component, ReactNode, ErrorInfo } from 'react';

type Props = { children: ReactNode; fallback?: (e: Error) => ReactNode };
type State = { error: Error | null };

export class ErrorBoundary extends Component<Props, State> {
  state: State = { error: null };

  static getDerivedStateFromError(error: Error): State {
    return { error };
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    // エラー報告連携(Sentry等)
    console.error('ErrorBoundary:', error, info.componentStack);
    if (typeof window !== 'undefined' && (window as any).Sentry) {
      (window as any).Sentry.captureException(error);
    }
  }

  reset = () => this.setState({ error: null });

  render() {
    if (this.state.error) {
      if (this.props.fallback) return this.props.fallback(this.state.error);
      return (
        <div className="p-6 bg-rose-500/10 border border-rose-500/30 rounded-2xl">
          <h2 className="text-rose-300 font-semibold mb-2">エラーが発生しました</h2>
          <p className="text-sm text-zinc-400 mb-3">{this.state.error.message}</p>
          <button onClick={this.reset} className="px-3 py-1 rounded-lg bg-rose-500 text-white text-sm">
            再試行
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

// 使い方:
// <ErrorBoundary><MyComponent /></ErrorBoundary>

:LiHandPointer: 使い方

対象プロジェクトに該当ファイルをコピーして、props を流し込むだけ。

:LiAlertCircle: 注意事項

  • 依存パッケージを忘れず追加