-
Notifications
You must be signed in to change notification settings - Fork 37
/
ErrorBoundary.js
94 lines (79 loc) · 2.07 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* ErrorBoundary
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { ErrorMessage, ProductionError } from './components';
import css from './ErrorBoundary.css';
export default class ErrorBoundary extends Component {
static propTypes = {
children: PropTypes.node,
forceProductionError: PropTypes.bool,
onError: PropTypes.func,
onReset: PropTypes.func,
resetButtonLabel: PropTypes.node,
subTitle: PropTypes.node,
title: PropTypes.node,
};
constructor(props) {
super(props);
this.state = {
error: undefined,
stack: undefined,
};
}
componentDidCatch(error, info) {
if (this.props.onError) {
this.props.onError(error, info);
}
const { stack: errorStack } = error;
const { componentStack } = info;
const lines = `
${errorStack.toString()}
${componentStack.toString()}
`.split('\n')
// Remove empty lines
.filter(Boolean);
const stack = lines
// Remove the first line because it's the same as the error we get above
.splice(1, lines.length)
// Remove whitespace
.map(str => str.replace(/\s+/, ''))
.join('\n');
this.setState({ error: error.toString(), stack });
}
renderError = () => {
const { forceProductionError, title, subTitle, resetButtonLabel, onReset } = this.props;
const { error, stack } = this.state;
const isDevelopment = process.env.NODE_ENV === 'development';
if (isDevelopment && !forceProductionError) {
return (
<ErrorMessage
error={error}
stack={stack}
/>
);
}
return (
<ProductionError
error={error}
onReset={onReset}
resetButtonLabel={resetButtonLabel}
stackTrace={stack}
subTitle={subTitle}
title={title}
/>
);
}
render() {
const { error } = this.state;
if (error) {
return (
<div className={css.root} data-test-error-boundary>
{this.renderError()}
</div>
);
}
return this.props.children;
}
}