Created
February 6, 2024 10:02
-
-
Save Drag13/7ce5d7cbc0d3ed844cf548536a007564 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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