How to use react-error-boundary, handle errors in React Part II

How to use react-error-boundary, handle errors in React Part II

How to use react-error-boundary, handle errors in React Part II

Error boundaries are reset:

Additionally, react-error-boundary gives our code a mechanism to recover from errors that our error borders have detected. Reset keys and the resetErrorBoundary function given to the fallback component are used to do this.

Using a code block example pulled directly from the React documentation is the best method to demonstrate how this works:

function ErrorFallback({error, componentStack, resetErrorBoundary}) {

 return (

   <div role="alert">

     <p>Something went wrong:</p>

     <pre>{error.message}</pre>

     <pre>{componentStack}</pre>

     <button onClick={resetErrorBoundary}>Try again</button>

   </div>

 )

}

function Bomb() {

 throw new Error(' KABOOM ')

}

function App() {

 const [explode, setExplode] = React.useState(false)

 return (

   <div>

     <button onClick={() => setExplode(e => !e)}>toggle explode</button>

     <ErrorBoundary

       FallbackComponent={ErrorFallback}

       onReset={() => setExplode(false)}

       resetKeys={[explode]}

     >

       {explode ? <Bomb /> : null}

     </ErrorBoundary>

   </div>

 )

}

As we can see from the code above, a state Hook was developed and is now utilised to decide whether the App component presents an error-safe component or a Bomb component that throws errors. Additionally, reset keys were sent to the error boundary component. These reset keys control whether the internal state of the error boundary is reset. The internal state of the error boundary will be reset if one of the reset keys is changed while rendering.

No alt text provided for this image


On the other hand, invoking the resetComponent function causes our ErrorBoundary component's onResethandler to be called, at which point we set the value of our explosion state to false. This results in the rendering of an error-safe component by our app component.

We also have the onResetKeysChange handler, which is activated when the reset keys' values change, resetting the internal state of the error boundary.

hook useErrorHandler:

The react-error-boundary library's ability to let developers use error boundaries to catch issues that traditional React error boundaries wouldn't normally be able to is another another fantastic feature. As a result, we are now able to leverage error boundaries to detect mistakes in API queries, event handlers, and other areas of the code that are susceptible to failures.

The useErrorHandler Hook may be applied in one of two ways:

1.    then we may call handleError(error) and give in the error object, as in the example below. var handleError = useErrorHandler()

2.    When handling the error condition oneself or when receiving it from another Hook, useErrorHandler(error) is a handy function.

Using the first technique, we would detect issues in an API request as follows:

const App = () => {

 return (

   <ErrorBoundary

     FallbackComponent={CharacterFallback}

   >

     <ComponentWhereErrorMightOccur/>

   </ErrorBoundary>

 );

};

 

 

const ComponentWhereErrorMightOccur = () => {

 const handleError = useErrorHandler();

 const callAPI = () => {

   const result = fetch(apiURL)

   .then(

     (response) => response.json(),

     (error) => handleError(error))

   .then((data) => {

     return data["results"];

   });

   return result;

 };

 useEffect(() => {

   (async function () {

     await callAPI();

   })();

 }, []);

 return (

   ...

 );

};

As you can see, all we have to do is call our handleError function, which was returned by the useErrorHandle Hook, and send the error object returned by retrieving data from our API. Our mistake bounds are better off in this approach.

as HOC, withErrorBoundary function:

Utilizing the withErrorBoundary function as a higher order component (HOC) to handle issues within components is made possible by react-error-boundary. In this manner, error handling can be delegated to the function so that we can concentrate on creating components. The amount of code needed to implement the component and its tests is also reduced by this technique.

Here is an illustration of how to utilise this from the react-error-boundary documentation:

import {withErrorBoundary} from 'react-error-boundary'

 

const ComponentErrorBoundary = withErrorBoundary(ComponentThatMayError, {

 FallbackComponent: ErrorBoundaryFallbackComponent,

 onError(error, info) {

   // Do something with the error

   // E.g. log to an error logging client here

 },

})

 

const ui = <ComponentErrorBoundary />

Conclusion:

React developers may write less code and increase their error boundary capabilities to catch additional types of failures that would otherwise go undetected by standard error boundaries by using react-error-boundary.

To view or add a comment, sign in

Others also viewed

Explore content categories