Skip to content

Commit

Permalink
feat(app): add ErrorBoundary and Suspense overlay to catch rendering …
Browse files Browse the repository at this point in the history
…errors
  • Loading branch information
RobsonOlv committed Dec 15, 2023
1 parent 8964847 commit affb4c6
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
36 changes: 36 additions & 0 deletions src/components/error-boundary/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { useRouter } from 'next/router'
import { Component } from 'react'
import FiveHundredPage from 'pages/500'

import { getLogger } from 'utils/logging/log-util'

export class ErrorBoundary extends Component {
constructor(props) {
super(props)
this.state = { hasError: false }
}

static getDerivedStateFromError() {
return { hasError: true }
}

componentDidCatch(error, errorInfo) {
console.log(error, errorInfo)
}

render() {
if (this.state.hasError) {
return <h1>Error occur</h1>
}

return this.props.children
}
}

export const SuspenseFallback = (branch) => {
const { asPath } = useRouter()
const logger = getLogger('Suspense Fallback')
logger.error(`Error while processing ${asPath}`)

return <FiveHundredPage branch={branch} />
}
10 changes: 9 additions & 1 deletion src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import Layout from 'components/layout'
type Props = AppProps & {
Component: Page
}
import { ErrorBoundary, SuspenseFallback } from 'components/error-boundary'
import { Suspense } from 'react'

import TrackerProvider from 'utils/contexts/trackerContext'
import PreviewContextProvider from 'utils/contexts/preview'
Expand All @@ -40,7 +42,13 @@ function MyApp({ Component, pageProps }: Props) {
sectionSelected={pageProps.sectionSelected}
parentsArray={pageProps.parentsArray}
>
<Component {...pageProps} />
<ErrorBoundary>
<Suspense
fallback={<SuspenseFallback branch={pageProps.branch} />}
>
<Component {...pageProps} />
</Suspense>
</ErrorBoundary>
</Layout>
</PreviewContextProvider>
</IntlProvider>
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
"src/tests/cypress/support/commands.js"
"src/tests/cypress/support/commands.js",
"src/components/error-boundary/index.jsx"
],
"exclude": ["node_modules"]
}

0 comments on commit affb4c6

Please sign in to comment.