forked from storefront-foundation/react-storefront
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathErrorBoundary.js
66 lines (54 loc) · 1.63 KB
/
ErrorBoundary.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import React, { Component } from 'react'
import PropTypes from 'prop-types'
/**
* An internal component that catches errors durring rendering, sets the
* error, stack, and page properties of the app state accordingly, and calls
* the registered error reporter if one is configured.
*/
export default class ErrorBoundary extends Component {
static propTypes = {
/**
* A function to call whenever an error occurs. The function is passed an
* object with `error` (the error message) and `stack` (the stack trace as a string).
*/
onError: PropTypes.func,
}
static defaultProps = {
onError: Function.prototype,
}
static getDerivedStateFromError(error) {
return { error }
}
state = {
error: null,
}
componentDidMount() {
const { onError } = this.props
this.windowErrorEvent = window.addEventListener('error', event => {
onError({ error: event.error })
})
this.windowUnhandledRejectionEvent = window.addEventListener('unhandledrejection', event => {
onError({ error: event.reason })
})
}
componentWillUnmount() {
window.removeEventListener('error', this.windowErrorEvent)
window.removeEventListener('unhandledrejection', this.windowUnhandledRejectionEvent)
}
/**
* When an error is caught, call the error reporter and update the app state
* @param {Error} error
* @param {Object} info
*/
componentDidCatch(error, info) {
const { onError } = this.props
// report the error
onError({ error })
}
render() {
if (this.state.error) {
return <div>{this.state.error.message}</div>
}
return this.props.children
}
}