admin_ruspet/src/components/DiagnosticErrorBoundary.tsx

91 lines
4.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Component, type ErrorInfo, type ReactNode } from 'react'
import { Center, Stack, Title, Text, Button, Code, Box } from '@mantine/core'
import { IconAlertTriangle } from '@tabler/icons-react'
interface Props {
children: ReactNode
// Полноэкранный вариант — для самого верхнего "предохранителя" (main.tsx).
// Без него — занимает высоту родителя (для page-level использования
// внутри layout, где вокруг уже есть Header/Sidebar).
fullPage?: boolean
}
interface State {
error: Error | null
componentStack: string | null
}
// Общий ErrorBoundary. Используется дважды:
// 1) в main.tsx, оборачивая <App /> — последний рубеж на случай падения
// чего угодно (в т.ч. самого layout/sidebar);
// 2) в MainLayout.tsx, оборачивая <Outlet />, с key={location.pathname} —
// тогда падение ОДНОЙ страницы не рушит весь интерфейс: Header и
// Sidebar остаются рабочими, и переход на другую страницу сам
// пересоздаёт boundary и сбрасывает ошибку — reload не нужен.
export default class ErrorBoundary extends Component<Props, State> {
state: State = { error: null, componentStack: null }
static getDerivedStateFromError(error: Error) {
return { error }
}
componentDidCatch(error: Error, info: ErrorInfo) {
// 🆕 Логируем с максимумом контекста — пригодится и сейчас для
// диагностики (например, бага "белый экран после правки
// иерархии"), и впредь. Если подключите Sentry или аналог —
// отправляйте error + info отсюда же.
console.error('[ErrorBoundary] Необработанная ошибка рендера:', {
message: error.message,
stack: error.stack,
componentStack: info.componentStack,
url: window.location.href,
timestamp: new Date().toISOString(),
})
this.setState({ componentStack: info.componentStack ?? null })
}
handleReload = () => {
window.location.reload()
}
render() {
const { error, componentStack } = this.state
if (!error) {
return this.props.children
}
return (
<Center h={this.props.fullPage ? '100vh' : '100%'} p="xl">
<Stack gap="sm" maw={640} align="center">
<IconAlertTriangle size={40} color="var(--mantine-color-red-6)" />
<Title order={3} ta="center">
Произошла ошибка при загрузке страницы
</Title>
<Text c="dimmed" ta="center" size="sm">
Попробуйте перейти на другую страницу через меню слева или перезагрузить
страницу. Если ошибка повторяется — сообщите в техническую поддержку.
</Text>
<Button onClick={this.handleReload} mt="sm">
Перезагрузить страницу
</Button>
{import.meta.env.DEV && (
<Box mt="md" w="100%">
<Text size="xs" fw={600} c="dimmed" mb={4}>
Технические детали (видно только в dev-сборке):
</Text>
<Code
block
style={{ whiteSpace: 'pre-wrap', fontSize: 10, maxHeight: 240, overflow: 'auto' }}
>
{error.message}
{'\n\n'}
{componentStack}
</Code>
</Box>
)}
</Stack>
</Center>
)
}
}