How to auto send error of try catch block to Sentry in Node JS

Viewed 1111

I am building a Node JS application. I am using Sentry, https://docs.sentry.io/platforms/node/ in my application to monitor and report errors. But I am having a problem with global reporting for try catch block.

For example, I have a code block as follow.

const getUser = async (id) => {
  try {
     //do the database operation and return user
 } catch (e) {
    return {
      data: null,
      message: e.message
    }
 }
}

As you can see in the code, I am catching the error in the Try catch block. If I want to report the error to Sentry, I have to put in the following line in the catch block.

Sentry.captureException(e);

Basically, I am explicitly reporting the error. Is there a way to globally and automatically catch the error within the catch block and report it to the sentry. For, example, something like in PHP or Laravel. We will just have to initialize and configure the Sentry in one centralized place of the application and app will report any errors to the Sentry.

1 Answers

Sentry starts monitoring the whole application just by adding, the init function, somewhere in a global scope.

For example :

    Sentry.init({
  debug: appConfig.env === 'staging',
  dsn: appConfig.sentryDSN,
  environment: appConfig.env,
  integrations: [new Integrations.BrowserTracing()],
  release: [pjson.name, pjson.version].join('@'),
  tracesSampleRate: 1.0,
  ignoreErrors: [],
  normalizeDepth: 10, // Or however deep you want your state context to be.
  // (breadcrumb: Breadcrumb, hint?: BreadcrumbHint | undefined) => Breadcrumb | null
  beforeBreadcrumb(breadcrumb: Sentry.Breadcrumb, hint: Sentry.BreadcrumbHint | undefined) {
    return breadcrumb.category === 'xhr' ? breadcrumb : null;
  },
});

You can stay just to that 'conf/init' if you like, this captures some errors, which are: `every error that inherits from the 'Error' object, like: TypeError, RangeError, ReferenceError, SyntaxError, etc , for more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

But its better to handle the errors explicitly, and have the power to control what you want to send to Sentry(add/filter breadcrumbs, add tags, extra data etc).

In my reactjs app i have a middleware that all the errors are sent there, and inside there there is a logic..

Similarly i d suggest an error middleware where all the errors are send there, and at that middleware you exlicitly handle & send them to Sentry.

I assume the the tech stack node + express, so i d suggest, in the routes catch, to call next(error):

router.get('/path', function(req, res, next){
    const getUser = async (id) => {
    try {
       //do the database operation and return user
    } catch (error) {
      //return {
      //  data: null,
      //  message: e.message
      // }
      next(error)
    }
  }
})

**OR based on Express 5, route handlers that return Promise will call next(value) automatically when they reject or throw an error **:

app.get('/path', async function (req, res, next) {
  var user = await getUser(id)
  res.send(user)
})

And into the app.js, you put the error handler middleware where it handles the errors..:

app.use(function(err, req, res, next){
    // filter the error
    // send it to Sentry
    if(condition){
          // add custom breadcrumb
          Sentry.addBreadcrumb({
            type: Sentry.Severity.Error,
            category,
            message,
            level: Sentry.Severity.Error,
          });


         Sentry.configureScope((scope: any) => {
           scope.setTag('section', section);// add tag
           Sentry.captureException(error, scope); // capture the error
         });
     }
  })
Related