This Article will showcase what is the best practice to utilize error boundary to build a robust and fault tolerant react app. It includes: When to use Error Boundary, Build a Error Boundary HOC with Error Handling and Error Reporting.
A common practice to increase your systems reliability is to make your system fault-tolerant. Which means that your system must stay resilient even if there are errors produced by users, some parts of the systems, and upstream services.
One way to make your system fault-tolerant is to minimize the influence of errors. If one module receives an error, we don’t want it to affect the other modules.
React provides <ErrorBoundary />
to handle errors thrown by components. Currently, most application only use it to catch and handle errors at app level(highest level). This means that once any component in your app throws an error, the whole application will crash.
Throwing error at an unimportant filter component, causing the whole application crash.
1 | function App() { |
The above code will crash the whole application!
Remix provides a way to handle errors at router level, each part of the application is nested router, and we can use <ErrorBoundary />
to handle errors for each router.
Without router level error boundary, the error will crash the whole application.
With router level error boundary, the error will only crash the router.
It is infeasible to add ErrorBoundary to every component. This will dramatically increase code complexity. We need to make trade-offs to balance code maintainability and error handling scope.
We wanna minimize the influence of errors. However, some components work together to form a complete use flow. For example, different portions of a form, any portion breaks inside the form. It is meaningless to keep other parts of the form working. So we will add Error Boundary at the form level, so that any part of the form breaking won’t affect other features like tables, search and so on.
Some components indeed are very easy to produce errors, and themselves aren’t very important features. In this case, we wanna add component level error handling to these components too, for example, filter, search features at table. Components are error-prone when:
To reduce the effort of adding component level error handling, we can create a HOC to wrap the component with error handling and error reporting feature.
1 | import { ErrorBoundary } from 'react-error-boundary'; |
1 | // usage: add boundary to your component |
Features:
error-boundary, error-handling, fault-tolerance, frontend, react, reliability, robustness — May 6, 2024
Made with ❤ and at Earth.