Skip to content

Instantly share code, notes, and snippets.

@JoaoVictor6
Last active June 18, 2023 17:29
Show Gist options
  • Select an option

  • Save JoaoVictor6/487b3f8f26603e3f7f1147909baf47e0 to your computer and use it in GitHub Desktop.

Select an option

Save JoaoVictor6/487b3f8f26603e3f7f1147909baf47e0 to your computer and use it in GitHub Desktop.
Error boundary with typescript example
import React, { ReactNode } from "react"
type ErrorInfo = {
componentStack: string
}
type ErrorBoundaryProps = {
children: ReactNode
}
type ErrorBoundaryState = {
hasError: boolean
}
export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props)
this.state = { hasError: false }
}
static getDerivedStateFromError(_error: unknown) {
return { hasError: true }
}
componentDidCatch(error: unknown, errorInfo: ErrorInfo) {
const componentName = errorInfo.componentStack.split(/at (\w+) /)[1]
if(error instanceof Error && import.meta.env.DEV) {
console.warn(`[${componentName} ERROR]`, {
...error,
componentStack: errorInfo
.componentStack.split('\n')
.map(content => content.trim())
.filter(Boolean)
})
}
}
render() {
const { hasError } = this.state
if (!hasError) {
return this.props.children
}
return (
<div>
<p>Ocorreu um erro ao renderizar este componente :(</p>
<button
type="button"
onClick={() => this.setState({ hasError: false })}
>
Tente novamente
</button>
</div>
)
}
}
export default ErrorBoundary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment