본문으로 건너뛰기

ErrorBoundary

Code

components/ErrorBoundary/index.tsx
import { Component } from 'react'
import type { ErrorInfo } from 'react'

interface Error {
stack?: string
}
interface Props {}
interface State {
hasError: boolean
}

class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = { hasError: false }
}

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

componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.log('componentDidCatch error: ')
console.dir(error)
console.log('componentDidCatch errorInfo: ')
console.dir(errorInfo)
}

render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>
}

return this.props.children
}
}

export default ErrorBoundary

References

https://ko.reactjs.org/docs/error-boundaries.html