43 lines
1.3 KiB
TypeScript
43 lines
1.3 KiB
TypeScript
import React from "react";
|
|
import { createContext } from "react";
|
|
|
|
interface ErrorBoundaryContextValue {
|
|
error: boolean;
|
|
message: string;
|
|
}
|
|
|
|
export const ErrorBoundaryContext = createContext<ErrorBoundaryContextValue | null>(null);
|
|
|
|
interface ErrorBoundaryProviderProps {
|
|
children: React.ReactNode;
|
|
fallback?: React.ReactNode;
|
|
}
|
|
|
|
interface ErrorBoundaryProviderState {
|
|
hasError: boolean;
|
|
error: Error | null;
|
|
}
|
|
|
|
export class ErrorBoundaryProvider extends React.Component<ErrorBoundaryProviderProps, ErrorBoundaryProviderState> {
|
|
constructor(props: ErrorBoundaryProviderProps) {
|
|
super(props);
|
|
this.state = { hasError: false, error: null };
|
|
}
|
|
|
|
static getDerivedStateFromError(error: Error): ErrorBoundaryProviderState {
|
|
return { hasError: true, error: error };
|
|
}
|
|
|
|
render() {
|
|
return <ErrorBoundaryContext.Provider value={{
|
|
error: this.state.hasError,
|
|
message: this.state.error ? this.state.error.toString() : ""
|
|
}}>
|
|
{this.state.hasError ? (
|
|
this.props.fallback ? this.props.fallback : <div>An error occurred: {this.state.error?.toString()}</div>
|
|
) : (
|
|
this.props.children
|
|
)}
|
|
</ErrorBoundaryContext.Provider>;
|
|
}
|
|
} |