summaryrefslogtreecommitdiff
path: root/apps/web/app/reader/_components/error-boundary.tsx
blob: 6696e6665f1fa8283ed8d25233ed246da3f7500e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"use client"

import { Component, type ReactNode } from "react"

interface ErrorBoundaryProperties {
  fallback?: ReactNode
  children: ReactNode
}

interface ErrorBoundaryState {
  hasError: boolean
  error: Error | null
}

export class ErrorBoundary extends Component<
  ErrorBoundaryProperties,
  ErrorBoundaryState
> {
  constructor(properties: ErrorBoundaryProperties) {
    super(properties)
    this.state = { hasError: false, error: null }
  }

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    return { hasError: true, error }
  }

  render() {
    if (this.state.hasError) {
      if (this.props.fallback) {
        return this.props.fallback
      }

      return (
        <div className="flex h-full items-center justify-center p-4">
          <div className="max-w-sm text-center">
            <p className="mb-2 text-text-primary">something went wrong</p>
            <p className="mb-4 text-text-dim">
              {this.state.error?.message ?? "an unexpected error occurred"}
            </p>
            <button
              type="button"
              onClick={() => this.setState({ hasError: false, error: null })}
              className="border border-border px-3 py-1 text-text-secondary transition-colors hover:bg-background-tertiary hover:text-text-primary"
            >
              try again
            </button>
          </div>
        </div>
      )
    }

    return this.props.children
  }
}