---
title: "Usage"
url: https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage/
---

# Usage | Sentry for Node.js

##### Deprecation Warning

A new Node SDK has superseded this deprecated version. Sentry preserves this documentation for customers using the old client. We recommend using the [updated Node SDK](https://docs.sentry.io/platforms/javascript/guides/node.md) for your projects.

## [Capturing Errors](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#capturing-errors)

You can use `captureException` to manually report errors:

```javascript
try {
  throw new Error();
} catch (e) {
  // You can get eventId either as the synchronous return value, or via the callback
  var eventId = Raven.captureException(e, function (sendErr, eventId) {
    // This callback fires once the report has been sent to Sentry
    if (sendErr) {
      console.error("Failed to send captured exception to Sentry");
    } else {
      console.log("Captured exception and send to Sentry successfully");
    }
  });
}
```

The recommended usage pattern, though, is to run your entire program inside a Raven context:

```javascript
var Raven = require("raven");

Raven.config("___PUBLIC_DSN___").install();
Raven.context(function () {
  // all your stuff goes here
});
```

Raven will automatically catch and report any unhandled errors originating inside this function (or anything it calls, etc), so you don’t have to manually *captureException* everywhere. This also gives your code access to context methods. See below for more on contexts.

## [context/wrap](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#contextwrap)

`Raven.context` allows you to wrap any function to be immediately executed. Behind the scenes, this uses [domains](https://nodejs.org/api/domain.html) to wrap, catch, and record any exceptions originating from the function.

```javascript
Raven.context(function () {
  doSomething(a[0]);
});
```

`Raven.wrap` wraps a function in a similar way to `Raven.context`, but instead of invoking the function, it returns another function. This is especially useful when passing around a callback.

```javascript
var doIt = function () {
  // doing cool stuff
};

setTimeout(Raven.wrap(doIt), 1000);
```

We refer to code wrapped via `Raven.context` or `Raven.wrap` as being inside a context. Code inside a context has access to the `setContext`, `mergeContext`, and `getContext` methods for associating data with that context.

```javascript
Raven.setContext({
  user: {
    username: "lewis",
  },
});

Raven.mergeContext({
  tags: {
    component: "api",
  },
});

console.log(Raven.getContext());
// { user: ..., tags: ... }
```

A context most commonly corresponds to a request; if you’re using our Express middleware, each request is automatically wrapped in its own context, so you can use Raven’s context methods from inside any of your middleware or handlers. A context might also correspond to, say, a connection lifecycle or a job being handled in a worker process.

Notable keys that you might set include `user`, `tags`, and `extra`. These types of extra context data are detailed more under [Additional Data](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#raven-node-additional-data).

Since `domains` are not supported in native `Promise` until Node.js v8, version `>=8.0.0` is required if you want to have an access to the context in `Promise` rejections. When older version of Node.js is used, it’ll just be skipped and globally set context will be used instead. Context for regular error handlers and `context/wrap` calls is working in every version, including v0.x.

## [Tracking Users](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#tracking-users)

While a user is logged in, you can tell Sentry to associate errors with user data. This is really just a particular use of the context methods described above:

```javascript
Raven.setContext({
  user: {
    email: "matt@example.com",
    id: "123",
  },
});
```

This data is then included with any errors or messages, allowing you to see which users are affected by problems.

## [Capturing Messages](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#capturing-messages)

```javascript
client.captureMessage("Broken!", function (err, eventId) {
  // The message has now been sent to Sentry
});
```

## [Additional Data](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#additional-data)

All optional attributes are passed as part of the options to `captureException` and `captureMessage`.

`user`

User context for this event. Must be a mapping. Children can be any native JSON type.

```javascript
{
  user: {
    name: "matt";
  }
}
```

If you’re inside a context and your context data includes a `user` key, that data will be merged into this.

`request`

Alias: `req`. The `request` object associated with this event, from a Node http server, Express, Koa, or similar. Will be parsed for request details and user context from `request.user` if present. It will only pull out the data that’s handled by the server: `headers`, `method`, `host`, `protocol`, `url`, `query`, `cookies`, `body`, `ip` and `user`.

```javascript
app.use(function (req, res, next) {
  if (someError) {
    Raven.captureException(someError, { req: req });
  }
});
```

Note that the `Raven.requestHandler()` Express middleware adds the `req` object to the context for you automatically, so you won’t need to provide it manually.

`tags`

Tags to index with this event. Must be a mapping of strings.

```javascript
{
  tags: {
    key: "value";
  }
}
```

If you’re inside a context and your context data includes a *tags* key, that data will be merged into this. You can also set tags data globally to be merged with all events by passing a `tags` option to `config`.

`extra`

Additional context for this event. Must be a mapping. Children can be any native JSON type.

```javascript
{
  extra: {
    key: "value";
  }
}
```

If you’re inside a context and your context data includes an *extra* key, that data will be merged into this. You can also set extra data globally to be merged with all events by passing an `extra` option to `config`.

`fingerprint`

The fingerprint for grouping this event. Learn more how [Sentry groups errors](https://docs.sentry.io/concepts/data-management/event-grouping.md).

```javascript
{
  // don't group events from the same NODE_ENV together
  fingerprint: ["{{ default }}", process.env.NODE_ENV];
}
```

`level`

The level of the event. Defaults to `error`.

```javascript
{
  level: "warning";
}
```

Sentry is aware of the following levels:

* debug (the least serious)
* info
* warning
* error
* fatal (the most serious)

## [Recording Breadcrumbs](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#recording-breadcrumbs)

Breadcrumbs are records of server and application lifecycle events that can be helpful in understanding the state of the application leading up to a crash.

We can capture breadcrumbs and associate them with a context, and then send them along with any errors captured from that context:

```javascript
Raven.context(function () {
  Raven.captureBreadcrumb({
    message: "Received payment confirmation",
    category: "payment",
    data: {
      amount: 312,
    },
  });
  // errors thrown here will have breadcrumb attached
});
```

To learn more about what types of data can be collected via breadcrumbs, see the [breadcrumbs client API specification](https://docs.sentry.io/platforms/javascript/guides/node/enriching-events/breadcrumbs.md).

Raven can be configured to automatically capture breadcrubs for certain events including:

> * http/https requests
> * console log statements
> * postgres queries

Automatic breadcrumb collection is disabled by default. You can enable it with a config option:

```javascript
Raven.config("___PUBLIC_DSN___", {
  autoBreadcrumbs: true,
});
```

Or just enable specific types of automatic breadcrumbs:

```javascript
Raven.config("___PUBLIC_DSN___", {
  autoBreadcrumbs: {
    http: true,
  },
});
```

For more on configuring breadcrumbs, see [*Configuration*](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/config.md).

## [Event IDs](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#event-ids)

To make referencing an event easy (both by the developer and customer), you can get an event ID from any captured message or exception. It’s provided both as the synchronous return value of the capture method and as an argument to the callback:

```javascript
var eventId = Raven.captureException(e, function (sendErr, eventId2) {
  // eventId === eventId2
});
```

## [Promises](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#promises)

By default, Raven does not capture unhandled promise rejections. You can have it do so automatically:

```javascript
Raven.config("___PUBLIC_DSN___", {
  captureUnhandledRejections: true,
}).install();
```

## [Global Fatal Error Handler](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#global-fatal-error-handler)

The `install` method sets up a global listener for uncaught exceptions, and `context` and `wrap` can catch exceptions as well. These are situations where Raven catches what would otherwise be a fatal process-ending exception. A process should generally not continue to run after such events occur, (see [Node docs](https://nodejs.org/api/process.html#process_event_uncaughtexception)), so Raven has a concept of a “fatal error handler”. When Raven catches an otherwise-fatal exception, it will capture the exception (send it to Sentry) and then call the fatal error handler.

By default, the fatal error handler prints the error and then exits the process. If you want to do your own clean-up, pre-exit logging, or other shutdown procedures, you can provide your own fatal error handler as an argument to `install()`.

The fatal error handler callback will be the last thing called before the process should shut down. It can do anything necessary, including asynchronous operations, to make a best effort to clean up and shut down the process, but it should not throw, and it absolutely must not allow the process to keep running indefinitely. This means it should probably make an explicit `process.exit()` call.

After catching a fatal exception, Raven will make a best-effort attempt to send it to Sentry before it calls the fatal exception handler. If sending fails, a `sendErr` error object will be passed, and otherwise the `eventId` will be provided. In either case, the error object resulting in the shutdown is passed as the first parameter.

```javascript
Raven.install(function (err, sendErr, eventId) {
  if (!sendErr) {
    console.log(
      "Successfully sent fatal error with eventId " +
        eventId +
        " to Sentry:",
    );
    console.error(err.stack);
  }
  console.log("This is thy sheath; there rust, and let me die.");
  process.exit(1);
});
```

## [Events](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#events)

If you want to know if an event was logged or errored out, Raven instances emit two events, *logged* and *error*:

```javascript
Raven.on("logged", function () {
  console.log("Yay, it worked!");
});

Raven.on("error", function (e) {
  // The event contains information about the failure:
  //   e.reason -- raw response body
  //   e.statusCode -- response status code
  //   e.response -- raw http response object

  console.log("uh oh, couldn't record the event");
});

Raven.captureMessage("Boom");
```

## [Configuring the HTTP Transport](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#configuring-the-http-transport)

```javascript
Raven.config("___PUBLIC_DSN___", {
  transport: new raven.transports.HTTPSTransport({
    rejectUnauthorized: false,
  }),
});
```

## [Disable Raven](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#disable-raven)

Passing any falsey value as the DSN will disable sending events upstream:

```javascript
Raven.config(process.env.NODE_ENV === "production" && "___PUBLIC_DSN___");
```

## [Disable Console Alerts](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#disable-console-alerts)

Raven will print console alerts in situations where you’re using a deprecated API or where behavior might be surprising, like if there’s no DSN configured.

These alerts are hopefully helpful during initial setup or in upgrading Raven versions, but once you have everything set up and going, we recommend disabling them:

```javascript
Raven.disableConsoleAlerts();
```

## [Multiple Instances](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#multiple-instances)

Normally there is just one instance of Raven:

```javascript
var Raven = require("raven");
// Raven is already a Raven instance, and we do everything based on that instance
```

This should be sufficient for almost all users, but for various reasons some users might like to have multiple instances. Additional instances can be created like this:

```javascript
var Raven2 = new Raven.Client();
```

## [Dealing with Minified Source Code](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/usage.md#dealing-with-minified-source-code)

Raven and Sentry support [Source Maps](https://web.dev/articles/source-maps).

We have provided some instructions to creating Source Maps over at [Source Maps](https://docs.sentry.io/platforms/javascript/guides/node/legacy-sdk/sourcemaps.md).
