React Error Handling and Logging Best Practices

How to handle errors and properly log them using the right toolsFront-end developers often overlook error handling and logging. However, if any code segment throws an error, you must handle it correctly. Besides, depending on the situation, there are s…


This content originally appeared on Bits and Pieces - Medium and was authored by Manusha Chethiyawardhana

How to handle errors and properly log them using the right tools

React Error Handling and Logging Best Practices

Front-end developers often overlook error handling and logging. However, if any code segment throws an error, you must handle it correctly. Besides, depending on the situation, there are several ways to manage and log errors in React.

This article will go over best practices for error handling and logging in React for different scenarios. Let’s get started.

Error Handling — Best Practices

Proper error handling is critical for applications to function normally. And, let’s look at several practices around error handling.

1. Error handling with Error Boundaries — For class components

Error boundaries are the most straightforward and effective way to handle errors that occur within your React components.

You can create an error boundary component by including the life cycle method componentDidCatch(error, info) if you use class component. It is best to use this function to log error information to your preferred error logging service.

Besides, you can use the static function getDerivedStateFromError(error) to update the state and use the render() method to display a fallback UI if an error occurs.

An example error boundary component is shown below.

After that, you only need to wrap the required component(s) inside the error boundary component.

<ErrorBoundary>
<MyComponent />
</ErrorBoundary>

It is up to you to define the granularity of error boundaries. For example, you can wrap top-level route components in an error boundary to show the user a common error page or wrap individual widgets in an error boundary.

If an error occurs outside of an error boundary, the entire React component tree will be unmounted, causing your application to crash.

Therefore, ensure that error-prone components are wrapped in an error boundary component. Although error boundaries are an excellent way to deal with errors, they do have a few drawbacks. For example, the componentDidCatch(error, info) life cycle method is called only if an error occurs while rendering, in lifecycle methods, or constructors of any child component of the component.

As a result, error boundaries, cannot handle errors in event handlers, asynchronous callbacks, or server-side rendering.

2. Error handling with Try-Catch — Catch beyond boundaries

Try-catch blocks aren’t the best way to handle component-level exceptions because they don’t catch exceptions cascaded from child components.

However, try-catch blocks are used for dealing with errors that aren’t caught by error boundaries.

Consider a user signup scenario in which we make an asynchronous call to an API. There, we can use try-catch and React states to handle any errors that may occur.

Similarly, try-catch can be used in situations where error boundaries are ineffective. However, this can lead to code duplication in some cases.

3. Using react-error-boundary Library — The best way

The react-error-boundary library greatly simplifies error handling in React and is the most effective solution to overcome the limitations of the basic error boundaries.

It enables you to display a fallback component, log errors just like in the basic error boundaries, and reset the application’s state, so the error does not occur again.

More importantly, you can now handle errors in event handlers and asynchronous code using the useErrorHandler() custom hook.

If the useErrorHandler(error) hook is called with a truthy value for error, react-error-boundary will propagate that to the nearest error boundary.

So, you can use react-error-boundary to eliminate the need for two different error handling methods in your app.

Error Logging — Best Practices

Many developers are familiar with console logs, but only a few understand how to log errors in a React app persistently. Although console logs help in error root detection during development, they become ineffective once the application is deployed since it executes at the user’s browser.

Therefore, we need to create a backend error logging service or a third-party one to track errors.

Furthermore, log analysis can help us understand how application users interact with the application. This is useful for identifying the behaviors of users and security risks.

For example, a high number of failed login attempts may indicate that someone attempted to gain unauthorized access to your application.

Best Tools for Logging

You can use a third-party client-side logging service to log errors persistently. The following are some of the best logging service providers for React you can try out.

Sentry

Sentry provides a custom error boundary component for React, automatically sending JavaScript errors within a component tree to Sentry. You can use it similarly to React’s basic error boundary component.

React Error and Performance Monitoring

redux-logger

redux-logger also known as Logger for Redux allows you to create your own logger with custom options. It’s simple to use and allows for console and production-level logging customization.

Log level

Log level takes the place of the standard console.log() with level-based logging and filtering features that give you a lot more control over your logs. It has fewer features than Sentry or redux-logger, but it has the essential functionality that most of us require.

You can use loglevel-plugin-remote to send logs to a remote log server for storage, analysis, and alerts. Rather than sending plain text, you should send logs as JSON objects so that they can be easily sorted and organized.

Tip: Build better Component Libs and Design Systems

Share components across teams and projects to speed up development and make sure your users experience a consistent design at every touchpoint.

OSS Tools like Bit offer a great dev experience for building, sharing, and adopting components across teams and applications. Create a component hub for free give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Conclusion

Any high-quality application must handle errors and unexpected events. Errors should be handled and appropriately logged to assist you in determining the root cause of errors while having the least impact on the user experience.

This article discussed various approaches that could be used to accomplish this, and I hope it will help you develop more robust React applications.

Thank you for reading, and happy coding!

Learn More


React Error Handling and Logging Best Practices was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Manusha Chethiyawardhana


Print Share Comment Cite Upload Translate Updates
APA

Manusha Chethiyawardhana | Sciencx (2021-09-30T16:44:04+00:00) React Error Handling and Logging Best Practices. Retrieved from https://www.scien.cx/2021/09/30/react-error-handling-and-logging-best-practices/

MLA
" » React Error Handling and Logging Best Practices." Manusha Chethiyawardhana | Sciencx - Thursday September 30, 2021, https://www.scien.cx/2021/09/30/react-error-handling-and-logging-best-practices/
HARVARD
Manusha Chethiyawardhana | Sciencx Thursday September 30, 2021 » React Error Handling and Logging Best Practices., viewed ,<https://www.scien.cx/2021/09/30/react-error-handling-and-logging-best-practices/>
VANCOUVER
Manusha Chethiyawardhana | Sciencx - » React Error Handling and Logging Best Practices. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/09/30/react-error-handling-and-logging-best-practices/
CHICAGO
" » React Error Handling and Logging Best Practices." Manusha Chethiyawardhana | Sciencx - Accessed . https://www.scien.cx/2021/09/30/react-error-handling-and-logging-best-practices/
IEEE
" » React Error Handling and Logging Best Practices." Manusha Chethiyawardhana | Sciencx [Online]. Available: https://www.scien.cx/2021/09/30/react-error-handling-and-logging-best-practices/. [Accessed: ]
rf:citation
» React Error Handling and Logging Best Practices | Manusha Chethiyawardhana | Sciencx | https://www.scien.cx/2021/09/30/react-error-handling-and-logging-best-practices/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.