Skip to content

Instantly share code, notes, and snippets.

@Drag13
Created February 6, 2024 10:02
Show Gist options
  • Save Drag13/7ce5d7cbc0d3ed844cf548536a007564 to your computer and use it in GitHub Desktop.
Save Drag13/7ce5d7cbc0d3ed844cf548536a007564 to your computer and use it in GitHub Desktop.
type ErrorBoundariesProps<TContext> =
| {
children: ReactNode;
errorFallback: ReactNode | ((props: { error: Error }) => ReactNode);
onError?: (error: Error, context: TContext) => void;
}
| {
children: ReactNode;
errorFallback:
| ReactNode
| ((props: TContext & { error: Error }) => ReactNode);
context: TContext;
onError?: (error: Error, context: TContext) => void;
};
type ErrorBoundariesState =
| { hasError: false }
| { hasError: true; error: Error };
class ErrorBoundaries<TContext extends object> extends PureComponent<
ErrorBoundariesProps<TContext>,
ErrorBoundariesState
> {
state: ErrorBoundariesState = { hasError: false };
static getDerivedStateFromError(error: Error) {
return { hasError: true, error };
}
constructor(props: ErrorBoundariesProps<TContext>) {
super(props);
}
render() {
if (!this.state.hasError) {
return this.props.children;
}
const { errorFallback: ErrorComponent } = this.props;
if (typeof ErrorComponent === 'function') {
const ctx = 'context' in this.props ? this.props.context : {};
return <ErrorComponent {...(ctx as TContext)} error={this.state.error} />;
}
return ErrorComponent;
}
componentDidCatch(error: Error): void {
const { onError } = this.props;
if (onError) {
const ctx =
'context' in this.props ? this.props.context : ({} as TContext);
onError(error, ctx);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment