Added error boundary for all pages
Deploy Frontend / build-and-deploy (push) Successful in 31s
Details
Deploy Frontend / build-and-deploy (push) Successful in 31s
Details
This commit is contained in:
parent
31e7c6e92e
commit
31470f85cf
|
|
@ -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, оборачивая <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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,12 +1,14 @@
|
||||||
import { AppShell } from '@mantine/core'
|
import { AppShell } from '@mantine/core'
|
||||||
import { useDisclosure } from '@mantine/hooks'
|
import { useDisclosure } from '@mantine/hooks'
|
||||||
import { Outlet } from 'react-router-dom'
|
import { Outlet, useLocation } from 'react-router-dom'
|
||||||
import Sidebar from './Sidebar'
|
import Sidebar from './Sidebar'
|
||||||
import Header from './Header'
|
import Header from './Header'
|
||||||
|
import ErrorBoundary from '../DiagnosticErrorBoundary'
|
||||||
|
|
||||||
export default function MainLayout() {
|
export default function MainLayout() {
|
||||||
const [mobileOpened, { toggle: toggleMobile }] = useDisclosure()
|
const [mobileOpened, { toggle: toggleMobile }] = useDisclosure()
|
||||||
const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true)
|
const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true)
|
||||||
|
const location = useLocation()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AppShell
|
<AppShell
|
||||||
|
|
@ -32,7 +34,9 @@ export default function MainLayout() {
|
||||||
</AppShell.Navbar>
|
</AppShell.Navbar>
|
||||||
|
|
||||||
<AppShell.Main bg="gray.0" miw={0}>
|
<AppShell.Main bg="gray.0" miw={0}>
|
||||||
<Outlet />
|
<ErrorBoundary key={location.pathname}>
|
||||||
|
<Outlet />
|
||||||
|
</ErrorBoundary>
|
||||||
</AppShell.Main>
|
</AppShell.Main>
|
||||||
</AppShell>
|
</AppShell>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ import { theme } from './theme'
|
||||||
import '@mantine/core/styles.css'
|
import '@mantine/core/styles.css'
|
||||||
import '@mantine/notifications/styles.css'
|
import '@mantine/notifications/styles.css'
|
||||||
import '@mantine/dates/styles.css'
|
import '@mantine/dates/styles.css'
|
||||||
|
import ErrorBoundary from './components/DiagnosticErrorBoundary'
|
||||||
|
|
||||||
const queryClient = new QueryClient({
|
const queryClient = new QueryClient({
|
||||||
defaultOptions: {
|
defaultOptions: {
|
||||||
|
|
@ -27,7 +28,9 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||||
<MantineProvider theme={theme}>
|
<MantineProvider theme={theme}>
|
||||||
<ModalsProvider>
|
<ModalsProvider>
|
||||||
<Notifications position="top-right" />
|
<Notifications position="top-right" />
|
||||||
<App />
|
<ErrorBoundary fullPage>
|
||||||
|
<App />
|
||||||
|
</ErrorBoundary>
|
||||||
</ModalsProvider>
|
</ModalsProvider>
|
||||||
</MantineProvider>
|
</MantineProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue