Capture exceptions in all catch blocks

I have around 36 APIs written in Node.js(Express). All the APIs have try {...} catch {...} within the async function. I want to log to Sentry all errors that the caught in the catch block, but is there a way I set it up globally instead of writing Sentry.captureException(err) inside all the catch blocks?

The short answer is: no. Something’s got to tell sentry to capture the exception. There are many ways to do this. besides nesting each function within the same type of try…catch you could “decorate” (or wrap) your functions with your sentry handler.

I did something similar with a custom @decorator. If decorators are not your thing you might try creating a proxy.

That said, are you sure you want to captureException() and not addBreadcrumb()? throwing everything at sentry disregarding the context can produce a lot of unhelpful noise…

I was in a similar situation with my RN app, although I mainly needed to check for an Internet connection before initiating my API calls. What I did first was centralize my API calls to individual “model” functions instead of doing the calls themselves within individual components.

So, I created a bunch of get, find, update function for my “models” which indeed correspond to our API backend models.

So my structure was models/Job.js and within that I exposed the functions I needed.

Then what I did was create my own “wrapper” function that I called, creatively, myFetch.

What I do there is pass any arguments I would to a normal fetch() call but within the function I have my try...catch. Within the try I return fetch(args) and within the catch I still return a Promise.reject but also produce a Toast with a relevant message. You can, instead, log your error to Sentry and handle it gracefully for your own needs.

I did something similar in my Expo + Next app.

I have a hook for all my get requests (using useSWR). In this hook, I catch any exceptions, report them to sentry, and re-throw them so that my UI can handle them.

import useSWR, { responseInterface, keyInterface, ConfigInterface } from 'swr'
import * as Sentry from 'helpers/sentry'

export default function useGet<Data = any>(
  key: keyInterface,
  fn?: fetcherFn<Data>,
  config?: ConfigInterface<Data, ServerError>
): responseInterface<Data | null, ServerError> {
  return useSWR(
    key,
    (...key) => {
      try {
        return fn(...key)
      } catch (e) {
        Sentry.captureException(e)
        throw e
      }
    },
    config
  )
}