异步上下文

了解如何在请求之间隔离 Sentry 作用域和面包屑。

默认情况下,Sentry SDK 会自动隔离每个请求的范围和面包屑。这意味着添加的任何面包屑或标签都将仅限于该请求。这对于防止面包屑和范围在请求之间泄漏非常有用。以下是一个示例:

Copied
const Sentry = require("@sentry/node");

app.get("/my-route", function () {
  Sentry.addBreadcrumb({
    message: "This breadcrumb should only be attached to this request",
  });
  // do something
});

app.get("/my-route-2", function () {
  Sentry.addBreadcrumb({
    message: "This breadcrumb should only be attached to this request",
  });
  // do something
});

每个请求将有自己的面包屑,并且它们不会在请求之间共享。

如果你想手动隔离某些代码,例如后台作业,可以使用 withIsolationScope 方法。这将确保添加的任何面包屑或标签仅限于提供的回调内部:

Copied
const Sentry = require("@sentry/node");

async function backgroundJob() {
  return await Sentry.withIsolationScope(async () => {
    // Everything inside of this will be isolated
    await doSomething();
  });
}

在内部,SDK 使用 Node.js 的 AsyncLocalStorage API 来执行隔离。