forked from alibaba-fusion/next
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror-boundary.jsx
63 lines (54 loc) · 1.61 KB
/
error-boundary.jsx
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
import React from 'react';
import PropTypes from 'prop-types';
DefaultUI.propTypes = {
error: PropTypes.object,
errorInfo: PropTypes.object,
};
function DefaultUI() {
return '';
}
export default class ErrorBoundary extends React.Component {
static propTypes = {
children: PropTypes.element,
/**
* 捕获错误后的自定义处理, 比如埋点上传
* @param {Object} error 错误
* @param {Object} errorInfo 错误详细信息
*/
afterCatch: PropTypes.func,
/**
* 捕获错误后的展现 自定义组件
* @param {Object} error 错误
* @param {Object} errorInfo 错误详细信息
* @returns {Element} 捕获错误后的处理
*/
fallbackUI: PropTypes.func,
};
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch(error, errorInfo) {
this.setState({
error: error,
errorInfo: errorInfo,
});
const { afterCatch } = this.props;
if ('afterCatch' in this.props && typeof afterCatch === 'function') {
this.props.afterCatch(error, errorInfo);
}
}
render() {
const { fallbackUI: FallbackUI = DefaultUI } = this.props;
if (this.state.errorInfo) {
return (
<FallbackUI
error={this.state.error}
errorInfo={this.state.errorInfo}
/>
);
}
// Normally, just render children
return this.props.children;
}
}