diff --git a/src/components/DiagnosticErrorBoundary.tsx b/src/components/DiagnosticErrorBoundary.tsx new file mode 100644 index 0000000..317005c --- /dev/null +++ b/src/components/DiagnosticErrorBoundary.tsx @@ -0,0 +1,91 @@ +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, оборачивая — последний рубеж на случай падения +// чего угодно (в т.ч. самого layout/sidebar); +// 2) в MainLayout.tsx, оборачивая , с key={location.pathname} — +// тогда падение ОДНОЙ страницы не рушит весь интерфейс: Header и +// Sidebar остаются рабочими, и переход на другую страницу сам +// пересоздаёт boundary и сбрасывает ошибку — reload не нужен. +export default class ErrorBoundary extends Component { + 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 ( +
+ + + + Произошла ошибка при загрузке страницы + + + Попробуйте перейти на другую страницу через меню слева или перезагрузить + страницу. Если ошибка повторяется — сообщите в техническую поддержку. + + + + {import.meta.env.DEV && ( + + + Технические детали (видно только в dev-сборке): + + + {error.message} + {'\n\n'} + {componentStack} + + + )} + +
+ ) + } +} \ No newline at end of file diff --git a/src/components/Layout/MainLayout.tsx b/src/components/Layout/MainLayout.tsx index b458921..cf5c1aa 100644 --- a/src/components/Layout/MainLayout.tsx +++ b/src/components/Layout/MainLayout.tsx @@ -1,12 +1,14 @@ import { AppShell } from '@mantine/core' import { useDisclosure } from '@mantine/hooks' -import { Outlet } from 'react-router-dom' +import { Outlet, useLocation } from 'react-router-dom' import Sidebar from './Sidebar' import Header from './Header' +import ErrorBoundary from '../DiagnosticErrorBoundary' export default function MainLayout() { const [mobileOpened, { toggle: toggleMobile }] = useDisclosure() const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true) + const location = useLocation() return ( - + + + ) diff --git a/src/main.tsx b/src/main.tsx index d77471d..670b2f6 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -10,6 +10,7 @@ import { theme } from './theme' import '@mantine/core/styles.css' import '@mantine/notifications/styles.css' import '@mantine/dates/styles.css' +import ErrorBoundary from './components/DiagnosticErrorBoundary' const queryClient = new QueryClient({ defaultOptions: { @@ -27,7 +28,9 @@ ReactDOM.createRoot(document.getElementById('root')!).render( - + + +