Intro
Wrong solution:
function Calculator({ left, operator, right }) { try { const resul = operations[operator](left, right) return ( <div> <code> {left} {operator} {right} = <output>{result}</output> </code> </div> ) } catch (error) { return <div>Oh no! An error occurred! </div> } }
Reikia apgaubti pati App komponenta
<ErrorBoundary fallback={<div>Oh no!</div>}>
<App />
</ErrorBoundary>
Realizacija
class ErrorBoundary extends React.Component {
state = { error: null }
static getDerivedStateFromError(error) {
return { error }
}
render() {
return this.state.error? this.props. fallback this.props.children
}
}
Async realizacija
function App() {
const { showBoundary } = useErrorBoundary()
useEffect (() => {
function handleMouseMove(event) {
try {
// Do something that could throw
} catch (error) {
showBoundary(error)
}
}
window.addEventListener('mousemove', handleMouseMove)
return () => {
window.removeEventListener('mousemove', handleMouseMove)
}
})
// Render
}
Dar pvz:
function App() {
return (
<div>
<ErrorBoundary fallback={<div>Something went wrong with the list. </div>}>
<List />
</ErrorBoundary>
<ErrorBoundary fallback={<div>Something went wrong with this item, try another.</div>}
<Detail />
</ErrorBoundary>
</div>
)
}
Sprendimas
Naudojant react-error-boundary
import { createRoot } from 'react-dom/client'
// bring in ErrorBoundary and FallbackProps type from react-error-boundary importErrorBoundary, type FallbackProps } from 'react-error-boundary'
...
function ErrorFallback (props: FallbackProps) {
return (
<div role="alert">
<p>Something went wrong: </p>
<pre> {props.error.message}</pre>
</div>
)
}
...
function App() {
return (
<ErrorBoundary FallbackComponent={ErrorFallback}>
<OnboardingForm />
</ErrorBoundary>
)
}
async
import {
ErrorBoundary,
useErrorBoundary,
type FallbackProps,
} from 'react-error-boundary'
function OnboardingForm() {
const { showBoundary } = useErrorBoundary()
return (
<form
action="api/onboarding"
method="POST"
encType="multipart/form-data"
onSubmit={event => {
try {
event.preventDefault()
const formData = new FormData(event.currentTarget)
console.log(Object.fromEntries (formData))
const accountType = formData.get('accounType') as string
console.log(accountType.toUpperCase())
} catch (error) {
showBoundary(error)
}
}}
...
function ErrorFallback (props: FallbackProps) {
return (
<div role="alert">
<p>Something went wrong: </p>
<pre> {props.error.message}</pre>
</div>
)
}
...
function App() {
return (
<ErrorBoundary FallbackComponent={ErrorFallback}>
<OnboardingForm />
</ErrorBoundary>
)
}
Reset error (recreate new component instance without data (state)
resetErrorBoundary - fallback galima pasiimti reset boundary
function Error Fallback({ error, resetErrorBoundary }: FallbackProps) {
return (
<div role="alert">
There was an error: {' '}
<pre style={{ color: 'red', whiteSpace: 'normal' }}>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
)
}