Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add error boundary component #14

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions components/error-boundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
"use client";

import { assert } from "@acdh-oeaw/lib";
import { Component, createContext, type ErrorInfo, type ReactNode, use } from "react";

interface ErrorBoundaryContextValue {
error: Error;
reset: () => void;
}

const ErrorBoundaryContext = createContext<ErrorBoundaryContextValue | null>(null);

export function useErrorBoundary() {
const value = use(ErrorBoundaryContext);

assert(value != null, "`useErrorBoundary` must be used within an `ErrorBoundary` component.");

return value;
}

interface ErrorBoundaryProps {
children: ReactNode;
fallback: ReactNode;
onError?: (error: Error, errorInfo: ErrorInfo) => void;
}

type ErrorBoundaryState =
| {
status: "default";
error: null;
}
| {
status: "error";
error: Error;
};

const initialState: ErrorBoundaryState = {
status: "default",
error: null,
};

export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);

this.state = initialState;

this.reset = this.reset.bind(this);
}

static getDerivedStateFromError(error: unknown) {
return {
status: "error",
error: error instanceof Error ? error : new Error(`Error: ${String(error)}`),
};
}

componentDidCatch(error: Error, errorInfo: ErrorInfo) {
this.props.onError?.(error, errorInfo);
}

reset() {
this.setState(initialState);
}

render() {
if (this.state.status === "error") {
return (
// eslint-disable-next-line @typescript-eslint/unbound-method
<ErrorBoundaryContext.Provider value={{ error: this.state.error, reset: this.reset }}>
{this.props.fallback}
</ErrorBoundaryContext.Provider>
);
}

return this.props.children;
}
}
Loading