共享环境 / 浏览器扩展

了解如何在共享环境中使用 Sentry(例如在浏览器扩展或 VSCode 扩展中)。

我们建议在共享环境中使用 JavaScript SDK 8.x 及以上版本。请参阅我们的 迁移文档,以从旧版本 SDK 升级到 8.x 及以上版本。

这些最佳实践适用于以下使用场景:

  • 浏览器扩展
  • VSCode 扩展
  • 第三方小部件
  • 插件架构
  • 任何可能在同一环境中运行多个 Sentry 实例的其他场景

对于上述使用场景,请按照以下示例手动设置客户端。此外,避免添加使用全局状态的集成,如 BreadcrumbsGlobalHandlers。进一步地,一些使用全局状态的默认集成需要像下面的示例那样进行过滤。在这种情况下,最佳实践是避免使用任何集成,并依赖手动捕获错误。

Copied
import {
  BrowserClient,
  defaultStackParser,
  getDefaultIntegrations,
  makeFetchTransport,
  Scope,
} from "@sentry/browser";

// filter integrations that use the global variable
const integrations = getDefaultIntegrations({}).filter(
  (defaultIntegration) => {
    return !["BrowserApiErrors", "Breadcrumbs", "GlobalHandlers"].includes(
      defaultIntegration.name,
    );
  },
);

const client = new BrowserClient({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  transport: makeFetchTransport,
  stackParser: defaultStackParser,
  integrations: integrations,
});

const scope = new Scope();
scope.setClient(client);

client.init(); // initializing has to be done after setting the client on the scope

// You can capture exceptions manually for this client like this:
scope.captureException(new Error("example"));

为了使其更简单但仍保持 “让 Sentry 处理未处理的错误”,您可以使用以下代码:

Copied
// Init Sentry as shown above

try {
  // Your goes code here
  // as in import and execute your code here
  // and if an error occurs, Sentry will capture it
} catch (error) {
  scope.captureException(error);
}

如果您发现 Sentry 没有捕获来自浏览器扩展的错误事件,可能是启用了入站过滤器。您可以通过进入 项目设置 > 入站过滤器 并禁用过滤掉由浏览器扩展引起的已知错误来解决此问题。

了解更多关于入站过滤器的信息,请参阅产品文档中的 入站过滤器

自版本 8.37.0 起在所有基于浏览器的 SDK 中可用

如果由于某种原因,SDK 错误地检测到它是在浏览器扩展中初始化的,您可以通过指定跳过此检查:

Copied
import * as Sentry from "@sentry/browser";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  skipBrowserExtensionCheck: true,
  // ...
});

此选项纯粹是为了应对我们的浏览器扩展检查错误检测到浏览器扩展的情况。 例如,这可能是一个暴露类似浏览器扩展的全局 API 的跨平台应用程序框架。