In react two error handling phase methos are available
The static method getDerivedStateFromError is used to render a fallback UI after an error is thrown and the componentDidCatch method is used to log the error information.
We can get more idea by looking below example. you can put this file in /src/components folder and put
While we run above code, it will show error screen in browser. Actual error is in
Change in parent component as per below and add ErrorBoundary new component.
Now, above code shows, in browser 'Something went Wrong' only for second country component. other component will show as it expected. Now we log this error to console by componentDidCatch. So, add below code in ErrorBoundary component.
A class component becomes an Error Boundary by defining either or both of getDerivedStateFromError and componentDidCatch lifecycle methods.