Last active
June 18, 2023 17:29
-
-
Save JoaoVictor6/487b3f8f26603e3f7f1147909baf47e0 to your computer and use it in GitHub Desktop.
Error boundary with typescript example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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