Every React project should have an errorHandler

Onur Temiz
2 min readNov 2, 2021

--

I have been learning and using the React library for the past one and a half years, and when I look at my first React projects, I recognize that there was a lot of duplication on my try and catch blocks!

An example code:

try {await apiStuff() // might result in error} catch {Sentry.captureException(error) // Capturing error with Sentrynotify.error({ message: ‘Error!’, description: ‘Something went wrong!’ }) // A React component to notify the user}

Here, I am using a notification library, and that library comes with a object called notify.

With this object’s error function, I can show notifications whenever I want.

The problem with this approach is that what if I want to change the notification library to something else?

It is common to have more than 100+ try-catch blocks that have this function. We should not update all of them every time we want to change the library.

What if you want to add Sentry to your project and catch some of the problems with it. Should you add Sentry.captureException(error); line to everywhere?

I am just at the start of my career; however, one thing I learned is that:

If you are not building applications just for fun or small sizes, you should wrap the actual functionality inside another function whenever possible.

As a result, creating a function like down below will make your application more robust.

import * as Sentry from ‘@sentry/nextjs’import notification from ‘../notification’const errorHandler = (error, data) => {if (error) Sentry.captureException(error)if (data) notification.error(data)}export default errorHandler

You might notice that I use if statements to check whether error or data is present.

Error is optional because some errors are input errors, and there is nothing Sentry to catch.

Data is optional because sometimes, we do not want to show the error to the user.

--

--

No responses yet