|
| 1 | +import { Component, type ErrorInfo, type ReactNode } from "react"; |
| 2 | + |
| 3 | +interface ErrorBoundaryProps { |
| 4 | + children: ReactNode; |
| 5 | + fallback?: ReactNode; |
| 6 | +} |
| 7 | + |
| 8 | +interface ErrorBoundaryState { |
| 9 | + hasError: boolean; |
| 10 | + error: Error | null; |
| 11 | +} |
| 12 | + |
| 13 | +/** |
| 14 | + * Single root-level error boundary. Catches render errors (e.g. getCourseById |
| 15 | + * throwing on a missing course id) so a bad reference doesn't white-screen the |
| 16 | + * whole degree-audit page. |
| 17 | + * |
| 18 | + * Place one instance at the page root; don't scatter throughout the tree. |
| 19 | + */ |
| 20 | +export default class ErrorBoundary extends Component< |
| 21 | + ErrorBoundaryProps, |
| 22 | + ErrorBoundaryState |
| 23 | +> { |
| 24 | + state: ErrorBoundaryState = { hasError: false, error: null }; |
| 25 | + |
| 26 | + static getDerivedStateFromError(error: Error): ErrorBoundaryState { |
| 27 | + return { hasError: true, error }; |
| 28 | + } |
| 29 | + |
| 30 | + componentDidCatch(error: Error, info: ErrorInfo) { |
| 31 | + console.error("[Degree Audit Plus] Render error caught by ErrorBoundary:", error, info); |
| 32 | + } |
| 33 | + |
| 34 | + handleReset = () => { |
| 35 | + this.setState({ hasError: false, error: null }); |
| 36 | + }; |
| 37 | + |
| 38 | + render() { |
| 39 | + if (this.state.hasError) { |
| 40 | + if (this.props.fallback) return this.props.fallback; |
| 41 | + |
| 42 | + return ( |
| 43 | + <div className="flex min-h-screen w-full flex-col items-center justify-center gap-4 bg-background px-6 text-center text-text"> |
| 44 | + <h1 className="text-2xl font-bold text-dap-primary"> |
| 45 | + Something went wrong |
| 46 | + </h1> |
| 47 | + <p className="max-w-md text-sm text-dap-gray-light"> |
| 48 | + An unexpected error occurred while rendering your degree audit. |
| 49 | + Re-run your audit from the popup to refresh the data, or click the |
| 50 | + button below to try again. |
| 51 | + </p> |
| 52 | + {this.state.error && ( |
| 53 | + <pre className="max-w-lg rounded bg-gray-100 px-4 py-2 text-left text-xs text-red-600 dark:bg-gray-800"> |
| 54 | + {this.state.error.message} |
| 55 | + </pre> |
| 56 | + )} |
| 57 | + <button |
| 58 | + onClick={this.handleReset} |
| 59 | + className="rounded-md bg-dap-primary px-4 py-2 text-sm font-semibold text-white hover:opacity-90" |
| 60 | + > |
| 61 | + Try again |
| 62 | + </button> |
| 63 | + </div> |
| 64 | + ); |
| 65 | + } |
| 66 | + |
| 67 | + return this.props.children; |
| 68 | + } |
| 69 | +} |
0 commit comments