|
| 1 | +/** |
| 2 | + * Copyright (c) Facebook, Inc. and its affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + * |
| 7 | + * @flow |
| 8 | + */ |
| 9 | + |
| 10 | +import * as React from 'react'; |
| 11 | +import {Component, Suspense} from 'react'; |
| 12 | +import ErrorView from './ErrorView'; |
| 13 | +import SearchingGitHubIssues from './SearchingGitHubIssues'; |
| 14 | +import SuspendingErrorView from './SuspendingErrorView'; |
| 15 | + |
| 16 | +type Props = {| |
| 17 | + children: React$Node, |
| 18 | +|}; |
| 19 | + |
| 20 | +type State = {| |
| 21 | + callStack: string | null, |
| 22 | + componentStack: string | null, |
| 23 | + errorMessage: string | null, |
| 24 | + hasError: boolean, |
| 25 | +|}; |
| 26 | + |
| 27 | +const InitialState: State = { |
| 28 | + callStack: null, |
| 29 | + componentStack: null, |
| 30 | + errorMessage: null, |
| 31 | + hasError: false, |
| 32 | +}; |
| 33 | + |
| 34 | +export default class ErrorBoundary extends Component<Props, State> { |
| 35 | + state: State = InitialState; |
| 36 | + |
| 37 | + static getDerivedStateFromError(error: any) { |
| 38 | + const errorMessage = |
| 39 | + typeof error === 'object' && |
| 40 | + error !== null && |
| 41 | + error.hasOwnProperty('message') |
| 42 | + ? error.message |
| 43 | + : '' + error; |
| 44 | + |
| 45 | + return { |
| 46 | + errorMessage, |
| 47 | + hasError: true, |
| 48 | + }; |
| 49 | + } |
| 50 | + |
| 51 | + componentDidCatch(error: any, {componentStack}: any) { |
| 52 | + const callStack = |
| 53 | + typeof error === 'object' && |
| 54 | + error !== null && |
| 55 | + error.hasOwnProperty('stack') |
| 56 | + ? error.stack |
| 57 | + .split('\n') |
| 58 | + .slice(1) |
| 59 | + .join('\n') |
| 60 | + : null; |
| 61 | + |
| 62 | + this.setState({ |
| 63 | + callStack, |
| 64 | + componentStack, |
| 65 | + }); |
| 66 | + } |
| 67 | + |
| 68 | + render() { |
| 69 | + const {children} = this.props; |
| 70 | + const {callStack, componentStack, errorMessage, hasError} = this.state; |
| 71 | + |
| 72 | + if (hasError) { |
| 73 | + return ( |
| 74 | + <ErrorView |
| 75 | + callStack={callStack} |
| 76 | + componentStack={componentStack} |
| 77 | + errorMessage={errorMessage}> |
| 78 | + <Suspense fallback={<SearchingGitHubIssues />}> |
| 79 | + <SuspendingErrorView |
| 80 | + callStack={callStack} |
| 81 | + componentStack={componentStack} |
| 82 | + errorMessage={errorMessage} |
| 83 | + /> |
| 84 | + </Suspense> |
| 85 | + </ErrorView> |
| 86 | + ); |
| 87 | + } |
| 88 | + |
| 89 | + return children; |
| 90 | + } |
| 91 | +} |
0 commit comments