Usage

You can use captureException to manually report errors:

Copied
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:

Copied
var Raven = require("raven");

Raven.config("https://examplePublicKey@o0.ingest.sentry.io/0").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.

Raven.context allows you to wrap any function to be immediately executed. Behind the scenes, this uses domains to wrap, catch, and record any exceptions originating from the function.

Copied
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.

Copied
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.

Copied
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.

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.

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:

Copied
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.

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

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.

Copied
{
  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.

Copied
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.

Copied
{
  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.

Copied
{
  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.

Copied
{
  // 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.

Copied
{
  level: "warning";
}

Sentry is aware of the following levels:

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

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:

Copied
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.

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:

Copied
Raven.config("https://examplePublicKey@o0.ingest.sentry.io/0", {
  autoBreadcrumbs: true,
});

Or just enable specific types of automatic breadcrumbs:

Copied
Raven.config("https://examplePublicKey@o0.ingest.sentry.io/0", {
  autoBreadcrumbs: {
    http: true,
  },
});

For more on configuring breadcrumbs, see Configuration.

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:

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

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

Copied
Raven.config("https://examplePublicKey@o0.ingest.sentry.io/0", {
  captureUnhandledRejections: true,
}).install();

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), 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.

Copied
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);
});

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

Copied
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");

Copied
Raven.config("https://examplePublicKey@o0.ingest.sentry.io/0", {
  transport: new raven.transports.HTTPSTransport({
    rejectUnauthorized: false,
  }),
});

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

Copied
Raven.config(process.env.NODE_ENV === "production" && "https://examplePublicKey@o0.ingest.sentry.io/0");

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:

Copied
Raven.disableConsoleAlerts();

Normally there is just one instance of Raven:

Copied
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:

Copied
var Raven2 = new Raven.Client();

Raven and Sentry support Source Maps.

We have provided some instructions to creating Source Maps over at Source Maps.

Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").