How to handle errors in React?

Handling errors is an essential part of building robust and reliable applications. React provides several mechanisms to handle errors gracefully, ensuring a smooth user experience and preventing crashes. In this blog post, we will explore the different techniques for error handling in React.

Understanding Errors in React

Before diving into error handling techniques, it’s essential to understand the types of errors you might encounter in a React application. React errors can be categorized into two main types:

  • Compile-time Errors: These occur during the development phase and are related to syntax or logic errors in your code. They are typically caught by the build tools, such as Babel or TypeScript.
  • Runtime Errors: These occur during the execution of the application. They might result from unexpected inputs, network issues, or other runtime conditions.

Using ‘react-error-boundary’ Library

To implement Error Boundaries in functional components, the ‘react-error-boundary’ library provides a convenient way to do so. Here’s a brief example of how you can use it:

import { ErrorBoundary, useErrorHandler } from 'react-error-boundary'; function ErrorFallback({ error, resetErrorBoundary }) {   // Your custom error UI   return (     <div>       <h2>Something went wrong</h2>       <p>{error.message}</p>       <button onClick={resetErrorBoundary}>Try again</button>     </div>   ); } function MyComponent() {   const handleError = useErrorHandler();   // Any code that might throw an error   if (/* some condition */) {     throw new Error('This is an example error');   }   return (     <div>       {/* Your component content */}     </div>   ); } function App() {   return (     <ErrorBoundary FallbackComponent={ErrorFallback} onReset={onResetFunct}>       <MyComponent />     </ErrorBoundary>   ); } export default App;
Code language: JavaScript (javascript)

In this example, ‘ErrorBoundary’ is used to wrap the component tree where errors should be caught. The ‘FallbackComponent’ prop allows you to specify a custom UI to display when an error occurs.

Global Error Handling

In addition to local error handling, it is often useful to have a global error handler to capture any unhandled errors throughout your application. Here are some commonly used techniques for global error handling in React;

Window.onerror

The window.onerror event handler allows you to catch unhandled errors that occur outside of the React component hierarchy. You can register it in your main entry file:

import { useEffect } from 'react'; function App() {   useEffect(() => {     const handleGlobalError = (event) => {       // Log the error or perform other actions       console.error(event.error);     };     window.addEventListener('error', handleGlobalError);     return () => {       window.removeEventListener('error', handleGlobalError);     };   }, []);  // Your component code } export default App;
Code language: JavaScript (javascript)

Route Error Handling

If you’re working with a routing library and want to handle errors related to routing, you can use a ‘useRouteError’ hook.

import { Link, useRouteError } from 'react-router-dom'; const Error = () => {   const error = useRouteError();   console.log(error);   if (error.status === 404) {     return (       <>         <div>           <img src={img} alt='not found' />           <h3>Ohh! page not found</h3>           <p>We can't seem to find the page you're looking for</p>           <Link to='/home'>back home</Link>         </div>       </>     );   }   return (     <>       <div>         <h3>something went wrong</h3>       </div>     </>   ); }; export default Error;
Code language: JavaScript (javascript)

Conclusion

Error handling is a critical aspect of building applications. React provides various options to handle errors, such as Error Boundaries and Error Handling Hooks. Additionally, global error-handling techniques can help capture unhandled errors. By implementing effective error-handling strategies, you can ensure a smoother user experience and make your React applications more reliable.

Remember to log errors or send them to an error-tracking service to gather insights and improve the quality of your application. 

Recent Post

Click to Copy