Setup Error Reporting in React
Let’s start by setting up error reporting in React. To do so, we’ll be using Sentry. Sentry is a great service for reporting and debugging errors. And it comes with a very generous free tier.
In this chapter we’ll sign up for a free Sentry account and configure it in our React app. And in the coming chapters we’ll be reporting the various frontend errors to it.
Let’s get started.
Create a Sentry Account
Head over to Sentry and hit Get Started.
Then enter your info and hit Create Your Account.
Next hit Create project.
For the type of project, select React.
Give your project a name.
And that’s it. Scroll down and copy the Sentry.init
line.
Install Sentry
Now head over to the React frontend/
directory and install Sentry.
$ pnpm add @sentry/react --save
We are going to be using Sentry across our app. So it makes sense to keep all the Sentry related code in one place.
Add the following to the top of your src/lib/errorLib.ts
.
import * as Sentry from "@sentry/react";
import config from "../config";
export interface ErrorInfoType {
[key: string | symbol]: string;
}
const isLocal = process.env.NODE_ENV === "development";
export function initSentry() {
if (isLocal) {
return;
}
Sentry.init({ dsn: config.SENTRY_DSN });
}
export function logError(error: unknown, errorInfo: ErrorInfoType | null = null) {
if (isLocal) {
return;
}
Sentry.withScope((scope) => {
errorInfo && scope.setExtras(errorInfo);
Sentry.captureException(error);
});
}
Add the SENTRY_DSN
below the const config = {
line in frontend/src/config.ts
.
SENTRY_DSN: "https://your-dsn-id-here@sentry.io/123456",
Make sure to replace https://your-dsn-id-here@sentry.io/123456
with the line we copied from the Sentry dashboard above.
We are using the isLocal
flag to conditionally enable Sentry because we don’t want to report errors when we are developing locally. Even though we all know that we rarely ever make mistakes while developing…
The logError
method is what we are going to call when we want to report an error to Sentry. It takes:
- An Error object in
error
. - And, an object with key-value pairs of additional info in
errorInfo
.
Next, let’s initialize our app with Sentry.
Add the following to the end of the imports in src/index.tsx
.
import { initSentry } from "./lib/errorLib";
initSentry()
Now we are ready to start reporting errors in our React app! Let’s start with the API errors.
For help and discussion
Comments on this chapter