2023-05-06 15:49:37 +08:00
|
|
|
import * as React from 'react';
|
2019-12-11 14:15:45 +08:00
|
|
|
import Alert from '.';
|
|
|
|
|
|
|
|
interface ErrorBoundaryProps {
|
|
|
|
message?: React.ReactNode;
|
|
|
|
description?: React.ReactNode;
|
2022-04-08 22:55:42 +08:00
|
|
|
children?: React.ReactNode;
|
2019-12-11 14:15:45 +08:00
|
|
|
}
|
|
|
|
|
2022-11-04 15:33:01 +08:00
|
|
|
interface ErrorBoundaryStates {
|
|
|
|
error?: Error | null;
|
|
|
|
info?: {
|
|
|
|
componentStack?: string;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryStates> {
|
2019-12-11 14:15:45 +08:00
|
|
|
state = {
|
|
|
|
error: undefined,
|
|
|
|
info: {
|
|
|
|
componentStack: '',
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
componentDidCatch(error: Error | null, info: object) {
|
|
|
|
this.setState({ error, info });
|
|
|
|
}
|
|
|
|
|
|
|
|
render() {
|
|
|
|
const { message, description, children } = this.props;
|
|
|
|
const { error, info } = this.state;
|
|
|
|
const componentStack = info && info.componentStack ? info.componentStack : null;
|
|
|
|
const errorMessage = typeof message === 'undefined' ? (error || '').toString() : message;
|
|
|
|
const errorDescription = typeof description === 'undefined' ? componentStack : description;
|
|
|
|
if (error) {
|
2019-12-18 12:25:43 +08:00
|
|
|
return (
|
2023-01-05 16:13:36 +08:00
|
|
|
<Alert
|
|
|
|
type="error"
|
|
|
|
message={errorMessage}
|
|
|
|
description={
|
|
|
|
<pre style={{ fontSize: '0.9em', overflowX: 'auto' }}>{errorDescription}</pre>
|
|
|
|
}
|
|
|
|
/>
|
2019-12-18 12:25:43 +08:00
|
|
|
);
|
2019-12-11 14:15:45 +08:00
|
|
|
}
|
|
|
|
return children;
|
|
|
|
}
|
|
|
|
}
|
2022-11-04 15:33:01 +08:00
|
|
|
|
|
|
|
export default ErrorBoundary;
|