|
1 | | -import * as React from 'react'; |
2 | 1 | import * as Sentry from '@sentry/browser'; |
| 2 | +import * as React from 'react'; |
3 | 3 |
|
4 | | -interface ErrorBoundaryProps {} |
| 4 | +export type ErrorBoundaryProps = { |
| 5 | + fallback?: React.ReactNode; |
| 6 | + fallbackRender?(error: Error | null, componentStack: string | null, resetErrorBoundary: () => void): React.ReactNode; |
| 7 | + onError?(error: Error, componentStack: string): void; |
| 8 | + onReset?(error: Error | null, componentStack: string | null): void; |
| 9 | +}; |
5 | 10 |
|
6 | | -interface ErrorBoundaryState { |
7 | | - hasError: boolean; |
8 | | -} |
| 11 | +type ErrorBoundaryState = { |
| 12 | + error: Error | null; |
| 13 | + componentStack: string | null; |
| 14 | +}; |
| 15 | + |
| 16 | +const INITIAL_STATE = { |
| 17 | + componentStack: null, |
| 18 | + error: null, |
| 19 | +}; |
9 | 20 |
|
10 | 21 | class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> { |
11 | | - constructor(props: ErrorBoundaryProps) { |
12 | | - super(props); |
13 | | - this.state = { |
14 | | - hasError: false, |
15 | | - }; |
16 | | - } |
| 22 | + public state: ErrorBoundaryState = INITIAL_STATE; |
17 | 23 |
|
18 | | - public static getDerivedStateFromError(_: Error): ErrorBoundaryState { |
19 | | - return { hasError: true }; |
| 24 | + public componentDidCatch(error: Error, { componentStack }: React.ErrorInfo): void { |
| 25 | + Sentry.withScope(scope => { |
| 26 | + scope.setExtra('componentStack', componentStack); |
| 27 | + Sentry.captureException(error); |
| 28 | + }); |
| 29 | + const { onError } = this.props; |
| 30 | + if (onError) { |
| 31 | + onError(error, componentStack); |
| 32 | + } |
| 33 | + this.setState({ error, componentStack }); |
20 | 34 | } |
21 | 35 |
|
22 | | - public componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void { |
23 | | - Sentry.captureException(Error); |
24 | | - console.log(error); |
25 | | - console.log(errorInfo.componentStack); |
26 | | - } |
| 36 | + public resetErrorBoundary = () => { |
| 37 | + const { onReset } = this.props; |
| 38 | + if (onReset) { |
| 39 | + onReset(this.state.error, this.state.componentStack); |
| 40 | + } |
| 41 | + this.setState(INITIAL_STATE); |
| 42 | + }; |
27 | 43 |
|
28 | 44 | public render(): React.ReactNode { |
29 | | - if (this.state.hasError) { |
30 | | - return null; |
| 45 | + const { fallback, fallbackRender } = this.props; |
| 46 | + const { error, componentStack } = this.state; |
| 47 | + |
| 48 | + if (error) { |
| 49 | + if (typeof fallbackRender === 'function') { |
| 50 | + return fallbackRender(error, componentStack, this.resetErrorBoundary); |
| 51 | + } |
| 52 | + if (React.isValidElement(fallback)) { |
| 53 | + return fallback; |
| 54 | + } |
| 55 | + |
| 56 | + throw new Error('No fallback component has been set'); |
31 | 57 | } |
| 58 | + |
32 | 59 | return this.props.children; |
33 | 60 | } |
34 | 61 | } |
|
0 commit comments