Skip to content

Instantly share code, notes, and snippets.

@ntnbst
Last active May 10, 2020 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ntnbst/37a0254d21bc9bd40feaf78247fb2896 to your computer and use it in GitHub Desktop.
Save ntnbst/37a0254d21bc9bd40feaf78247fb2896 to your computer and use it in GitHub Desktop.
This gist has a simple implementation of error boundary (errors that occurs in react callstack unlike - promises or async calls)
// Using react-error-boundary library to handle custom error component in case of dom failure
// Error boundary will render the fallback component to its decendents in case of failure
// So we can add multiple error boundaries according to project
import { useState } from 'react'
import ReactErrorBoundary from 'react-error-boundary'
const ErrorBoundary = ReactErrorBoundary.ErrorBoundary
function ErrorFallback ({ error }) {
return (
<div>
<p>Something went wrong!!</p>
<pre>{error.message}</pre>
</div>
)
}
function Bomb () {
throw new Error('💥 Caboom 💥')
}
function App () {
const [explode, setExplode] = useState(false)
return (
<ErrorBoundary fallbackComponent={ErrorFallback}>
<div>
<div>
<button onClick={setExplode(true)}>💣</button>
</div>
<div>
<ErrorBoundary fallbackComponent={ErrorFallback}>
{explode ? <Bomb /> : 'Push the button'}
</ErrorBoundary>
</div>
</div>
</ErrorBoundary>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment