Home > Software design >  Is it a good or bad practice to use React Error boundaries to handle fetch errors?
Is it a good or bad practice to use React Error boundaries to handle fetch errors?

Time:11-01

I got a requirement to handle an error in an asynchronous typeahead search bar (fetches to the backend when typing) in a component in a React app, so Error Boundaries came up to mind when thinking about how to handle them.

I was thinking about wrapping the search results in an Error boundary and throw an error up when the result response comes up invalid.

But then i thought should Error boundaries be used for more critical errors only? Is it really a good idea to handle a fetch error through it?

CodePudding user response:

This isn't a matter of good or bad practice. Error boundaries cannot be used to handle fetch errors, they are used to catch errors encountered during rendering or lifecycle methods, not in event handlers or async code.

But even if they could, I would still say using them for this case would be bad practice when a simple try/catch would suffice.

From the docs on error boundaries:

Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

and

Note

Error boundaries do not catch errors for:

  • Event handlers (learn more)
  • Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)
  • Server side rendering
  • Errors thrown in the error boundary itself (rather than its children)

Instead you should use a try/catch block.

  • Related