Angular

Angular is a web framework that empowers developers to build fast, reliable applications. Learn how to set it up with Sentry.

除了捕获错误,您还可以通过启用追踪来监控多个服务或应用程序之间的交互。您还可以通过会话重放更快地找到错误或性能问题的根本原因,观看用户会话的视频回放。

选择您希望安装的 Sentry 功能(除错误监控外),以获取相应的安装和配置说明。

Sentry 通过在应用程序运行时使用 SDK 来捕获数据。

Copied
npm install @sentry/angular --save

In its current major version, the Sentry Angular SDK only supports Angular 14 and newer.

If you're using an older version of Angular, you also need to use an older version of the SDK. See the table below for compatibility guidance:

Angular versionRecommended Sentry SDK
14 and newer@sentry/angular
12 or 13@sentry/angular-ivy@^7 (see Note) *
10 or 11@sentry/angular@^7 *
9 and below@sentry/angular@^6 *
AngularJS/1.x@sentry/browser@^6 with the AngularJS integration *

* These versions of the SDK are no longer maintained or tested. Version 7 might still receive bug fixes but we don't guarantee support.

The @sentry/angular-ivy package was an Ivy-compatible version of @sentry/angular in version 7 of the SDK. It's recommended to use this package if you're using Angular 12 or 13 to avoid build-time warnings. Functionality-wise, it's identical to @sentry/angular and you can simply replace all imports of @sentry/angular with @sentry/angular-ivy in our docs. Since version 8, @sentry/angular-ivy was removed and merged with @sentry/angular which is now Ivy-compatible by default.

配置应在应用程序生命周期的尽可能早阶段进行。

Once this is done, Sentry's Angular SDK captures all unhandled exceptions and transactions.

main.ts
Copied
import { bootstrapApplication } from "@angular/platform-browser";
import { appConfig } from "./app/app.config";
import { AppComponent } from "./app/app.component";

import * as Sentry from "@sentry/angular";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    // Registers and configures the Tracing integration,
    // which automatically instruments your application to monitor its
    // performance, including custom Angular routing instrumentation
    Sentry.browserTracingIntegration(),
    // Registers the Replay integration,
    // which automatically captures Session Replays
    Sentry.replayIntegration(),
  ],

  // Set tracesSampleRate to 1.0 to capture 100%
  // of transactions for tracing.
  // We recommend adjusting this value in production
  // Learn more at
  // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate
  tracesSampleRate: 1.0,

  // Set `tracePropagationTargets` to control for which URLs trace propagation should be enabled
  tracePropagationTargets: ["localhost", /^https:\/\/yourserver\.io\/api/],

  // Capture Replay for 10% of all sessions,
  // plus for 100% of sessions with an error
  // Learn more at
  // https://docs.sentry.io/platforms/javascript/session-replay/configuration/#general-integration-configuration
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
});

bootstrapApplication(AppComponent, appConfig).catch((err) =>
  console.error(err)
);

The Sentry Angular SDK exports a couple of Angular providers that are necessary to fully instrument your application. We recommend registering them in your app.config.ts or main app.module.ts:

app.config.ts
Copied
import {
  ApplicationConfig,
  ErrorHandler,
  inject,
  provideAppInitializer,
} from "@angular/core";
import { Router } from "@angular/router";

import * as Sentry from "@sentry/angular";

export const appConfig: ApplicationConfig = {
  providers: [
    // ...
    {
      provide: ErrorHandler,
      useValue: Sentry.createErrorHandler(),
    },
    {
      provide: Sentry.TraceService,
      deps: [Router],
    },
    provideAppInitializer(() => {
      inject(TraceService);
    }),
  ],
};

The Sentry.createErrorHandler function initializes a Sentry-specific ErrorHandler that automatically sends errors caught by Angular to Sentry. Learn how to further configure Sentry's ErrorHandler behavior here.

If you're using an NGModule-based application (app.module.ts), you can also dependency-inject the TraceService from inside your AppModule constructor, instead of providing APP_INITIALIZER:

app.module.ts
Copied
@NgModule({
  // ...
})
export class AppModule {
  constructor(trace: Sentry.TraceService) {}
}

根据您项目的设置方式,Sentry 错误中的堆栈跟踪可能不会显示为您的实际代码。

要解决此问题,请将源映射上传到 Sentry。最简单的方法是使用 Sentry 向导:

Copied
npx @sentry/wizard@latest -i sourcemaps

向导将引导您完成以下步骤:

  • 登录 Sentry 并选择一个项目
  • 安装必要的 Sentry 包
  • 配置您的构建工具以生成和上传源映射
  • 配置您的 CI 以上传源映射

有关源映射的更多信息或更多上传选项,请参阅我们的 源映射文档

此代码片段包含一个有意的错误,因此您可以立即测试设置是否正常工作。

Trigger a test error somewhere in your Angular app, for example in your main app component:

app.component.html
Copied
<button (click)="throwTestError()">Test Sentry Error</button>

Then, in your app.component.ts add:

app.component.ts
Copied
public throwTestError(): void {
  throw new Error("Sentry Test Error");
}

Errors triggered from within Browser DevTools are sandboxed and won't trigger an error handler. Place the snippet directly in your code instead.

了解更多关于手动捕获错误或消息的信息,请参阅我们的使用文档

要查看和解决记录的错误,请登录 sentry.io 并选择您的项目。单击错误标题将打开一个页面,您可以在其中查看详细信息并将其标记为已解决。