2019-03-22 00:32:48 +08:00
|
|
|
import React, { Component } from 'react';
|
|
|
|
import PropTypes from 'prop-types';
|
2024-03-07 01:28:18 +08:00
|
|
|
import logger, { generateLoggerStreams } from '/imports/startup/client/logger';
|
2019-03-22 00:32:48 +08:00
|
|
|
|
|
|
|
const propTypes = {
|
|
|
|
children: PropTypes.element.isRequired,
|
2024-03-07 01:28:18 +08:00
|
|
|
Fallback: PropTypes.element,
|
|
|
|
errorMessage: PropTypes.string,
|
|
|
|
};
|
|
|
|
|
|
|
|
const defaultProps = {
|
|
|
|
Fallback: null,
|
|
|
|
errorMessage: 'Something went wrong',
|
2019-03-22 00:32:48 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
class ErrorBoundary extends Component {
|
|
|
|
constructor(props) {
|
|
|
|
super(props);
|
2024-03-07 01:28:18 +08:00
|
|
|
this.state = { error: '', errorInfo: null };
|
|
|
|
}
|
|
|
|
|
|
|
|
componentDidMount() {
|
|
|
|
const data = JSON.parse((sessionStorage.getItem('clientStartupSettings')) || {});
|
|
|
|
const logConfig = data?.clientLog;
|
|
|
|
if (logConfig) {
|
|
|
|
generateLoggerStreams(logConfig).forEach((stream) => {
|
|
|
|
logger.addStream(stream);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
componentDidUpdate() {
|
|
|
|
const { code, error, errorInfo } = this.state;
|
|
|
|
const log = code === '403' ? 'warn' : 'error';
|
|
|
|
if (error || errorInfo) {
|
|
|
|
logger[log]({
|
|
|
|
logCode: 'Error_Boundary_wrapper',
|
|
|
|
extraInfo: { error, errorInfo },
|
|
|
|
}, 'generic error boundary logger');
|
|
|
|
}
|
2019-03-22 00:32:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
componentDidCatch(error, errorInfo) {
|
|
|
|
this.setState({
|
|
|
|
error,
|
|
|
|
errorInfo,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
render() {
|
2024-03-07 01:28:18 +08:00
|
|
|
const { error, errorInfo } = this.state;
|
|
|
|
const { children, Fallback, errorMessage } = this.props;
|
2019-03-22 00:32:48 +08:00
|
|
|
|
2024-03-07 01:28:18 +08:00
|
|
|
const fallbackElement = Fallback && error
|
|
|
|
? <Fallback error={error || {}} errorInfo={errorInfo} /> : <div>{errorMessage}</div>;
|
|
|
|
return (error
|
|
|
|
? fallbackElement
|
|
|
|
: children);
|
2019-03-22 00:32:48 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
ErrorBoundary.propTypes = propTypes;
|
2024-03-07 01:28:18 +08:00
|
|
|
ErrorBoundary.defaultProps = defaultProps;
|
|
|
|
|
|
|
|
export default ErrorBoundary;
|
2019-03-22 00:32:48 +08:00
|
|
|
|
2022-01-19 02:27:54 +08:00
|
|
|
export const withErrorBoundary = (WrappedComponent, FallbackComponent) => (props) => (
|
2019-03-22 00:32:48 +08:00
|
|
|
<ErrorBoundary Fallback={FallbackComponent}>
|
|
|
|
<WrappedComponent {...props} />
|
|
|
|
</ErrorBoundary>
|
|
|
|
);
|