80 lines
2.5 KiB
JavaScript
Executable File
80 lines
2.5 KiB
JavaScript
Executable File
import React from 'react';
|
||
import {
|
||
Box,
|
||
Alert,
|
||
AlertIcon,
|
||
AlertTitle,
|
||
AlertDescription,
|
||
Button,
|
||
VStack,
|
||
Container
|
||
} from '@chakra-ui/react';
|
||
|
||
class ErrorBoundary extends React.Component {
|
||
constructor(props) {
|
||
super(props);
|
||
this.state = { hasError: false, error: null, errorInfo: null };
|
||
}
|
||
|
||
static getDerivedStateFromError(error) {
|
||
return { hasError: true };
|
||
}
|
||
|
||
componentDidCatch(error, errorInfo) {
|
||
this.setState({
|
||
error: error,
|
||
errorInfo: errorInfo
|
||
});
|
||
}
|
||
|
||
render() {
|
||
if (this.state.hasError) {
|
||
return (
|
||
<Container maxW="lg" py={20}>
|
||
<VStack spacing={6}>
|
||
<Alert status="error" borderRadius="lg" p={6}>
|
||
<AlertIcon boxSize="24px" />
|
||
<Box>
|
||
<AlertTitle fontSize="lg" mb={2}>
|
||
页面出现错误!
|
||
</AlertTitle>
|
||
<AlertDescription>
|
||
页面加载时发生了未预期的错误,请尝试刷新页面。
|
||
</AlertDescription>
|
||
</Box>
|
||
</Alert>
|
||
|
||
{process.env.NODE_ENV === 'development' && (
|
||
<Box
|
||
w="100%"
|
||
bg="gray.50"
|
||
p={4}
|
||
borderRadius="lg"
|
||
fontSize="sm"
|
||
overflow="auto"
|
||
maxH="200px"
|
||
>
|
||
<Box fontWeight="bold" mb={2}>错误详情:</Box>
|
||
<Box as="pre" whiteSpace="pre-wrap">
|
||
{this.state.error && this.state.error.toString()}
|
||
{this.state.errorInfo.componentStack}
|
||
</Box>
|
||
</Box>
|
||
)}
|
||
|
||
<Button
|
||
colorScheme="blue"
|
||
onClick={() => window.location.reload()}
|
||
>
|
||
重新加载页面
|
||
</Button>
|
||
</VStack>
|
||
</Container>
|
||
);
|
||
}
|
||
|
||
return this.props.children;
|
||
}
|
||
}
|
||
|
||
export |