首页指南参考教程

使用 Sentry

有关安装和配置 Sentry 以进行崩溃报告的指南。


Sentry 是一个崩溃报告平台,可让你实时了解生产部署,并提供重现和修复崩溃的信息。

¥Sentry is a crash reporting platform that provides you with real-time insight into production deployments with info to reproduce and fix crashes.

它会通知你用户在使用你的应用时遇到的异常或错误,并在网络仪表板上为你组织它们。自动报告的异常包括堆栈跟踪、设备信息、版本和其他相关上下文。你还可以提供特定于你的应用的其他上下文,例如当前路由和用户 ID。

¥It notifies you of exceptions or errors that your users run into while using your app and organizes them for you on a web dashboard. Reported exceptions include stacktraces, device info, version, and other relevant context automatically. You can also provide additional context that is specific to your application such as the current route and user id.

Platform compatibility

Android DeviceAndroid EmulatoriOS DeviceiOS SimulatorWeb

安装和配置 Sentry

¥Install and configure Sentry

1

注册 Sentry 账户并创建项目

¥Sign up for a Sentry account and create a project

在继续安装 Sentry 之前,你需要确保已创建 Sentry 账户和项目:

¥Before proceeding with installing Sentry, you'll need to make sure you have created a Sentry account and project:

1.1

注册 Sentry(免费套餐每月最多支持 5,000 个事件),并在仪表板中创建一个项目。记下你的组织别名、项目名称和 DSN,因为稍后你将需要它们:

¥Sign up for Sentry (the free tier supports up to 5,000 events per month), and create a project in your Dashboard. Take note of your organization slug, project name, and DSN as you'll need them later:

  • 组织 slug 可在“组织设置”选项卡中找到

    ¥organization slug is available in your Organization settings tab

  • 项目名称可在项目的“设置”>“项目”选项卡中找到(在列表中找到它)

    ¥project name is available in your project's Settings > Projects tab (find it in the list)

  • DSN 位于项目的设置 > 项目 > 项目名称 > 客户端密钥 (DSN) 选项卡中。

    ¥DSN is available in your project's Settings > Projects > Project name > Client Keys (DSN) tab.

1.2

转到 开发者设置 > 身份验证令牌 页面并创建一个新的 组织身份验证令牌。该令牌自动确定源映射上传和发布创建的范围。保存。

¥Go to the Developer Settings > Auth Tokens page and create a new Organization Auth Token. The token is automatically scoped for Source Map Upload and Release Creation. Save it.

一旦你拥有了这些:组织 slug、项目名称、DSN 和身份验证令牌,你就可以继续了。

¥Once you have each of these: organization slug, project name, DSN, and auth token, you're all set to proceed.

2

安装@sentry/react-native

¥Install @sentry/react-native

在项目目录中运行以下命令来安装来自 Sentry 团队的官方 React Native 库:

¥Run the following command in your project directory to install the official React Native library from the Sentry team:

Terminal
npx expo install @sentry/react-native

3

应用配置

¥App configuration

配置 @sentry/react-native 可以通过配置插件完成。将插件添加到项目的 应用配置 文件中:

¥Configuring @sentry/react-native can be done through the config plugin. Add the plugin to your project's app config file:

app.json
{
  "expo": {
    "plugins": [
      [
        "@sentry/react-native/expo",
        {
          "organization": "sentry org slug, or use the `SENTRY_ORG` environment variable",
          "project": "sentry project name, or use the `SENTRY_PROJECT` environment variable",
          // If you are using a self-hosted instance, update the value of the url property
          // to point towards your self-hosted instance. For example, https://self-hosted.example.com/.
          "url": "https://sentry.io/"
        }
      ]
    ]
  }
}

接下来,在你想要创建版本并将源映射上传到 Sentry 的环境中,你需要将 SENTRY_AUTH_TOKEN 环境变量设置为 Sentry 身份验证令牌。如果你使用 EAS Build,则可以通过 创建名为 SENTRY_AUTH_TOKEN 的密钥 设置环境变量。

¥Next, in an environment where you want to create releases and upload sourcemaps to Sentry, you will need to set the SENTRY_AUTH_TOKEN environment variable to your Sentry auth token. If you are using EAS Build, you can set the environment variable by creating a secret named SENTRY_AUTH_TOKEN.

Sentry 身份验证令牌应安全存储。不要将其提交到公共存储库,并像对待任何其他敏感 API 密钥一样对待它。
Are you using this library in a bare React Native app?

如果你不使用 持续的原生生成 (CNG),那么你应该使用 @sentry/wizard

¥If you do not use Continuous Native Generation (CNG), then you should use the @sentry/wizard.

4

更新 Metro 配置

¥Update Metro configuration

Sentry 连接到 Metro 以将 "调试 ID" 注入到源映射中。此调试 ID 用于将源映射与版本关联起来。要启用此功能,你需要将以下内容添加到 Metro.config.js(如果你还没有该文件,请在项目的根目录中创建它):

¥Sentry hooks into Metro to inject a "debug ID" into your source maps. This debug ID is used to associate source maps with releases. To enable this, you need to add the following to your metro.config.js (if you don't have the file yet, create it in the root of your project):

metro.config.js
// This replaces `const { getDefaultConfig } = require('expo/metro-config');`
const { getSentryExpoConfig } = require('@sentry/react-native/metro');

// This replaces `const config = getDefaultConfig(__dirname);`
const config = getSentryExpoConfig(__dirname);

module.exports = config;

5

初始化哨兵

¥Initialize Sentry

将以下内容添加到应用的主文件(例如 App.js)中:

¥Add the following to your app's main file such as App.js:

import * as Sentry from '@sentry/react-native';

Sentry.init({
  dsn: 'YOUR DSN HERE',
  debug: true, // If `true`, Sentry will try to print out useful debugging information if something goes wrong with sending the event. Set it to `false` in production
});

现在用 Sentry 封装应用的根组件。这可能是 App.js 或 index.js,具体取决于你的项目。如果你使用的是 Expo Router,请参阅下面 与 Expo 路由一起使用 部分中的示例配置。

¥Now wrap the root component of your app with Sentry. This may be App.js or index.js depending on your project. If you are using Expo Router, see the example configuration in the Usage with Expo Router section below.

import * as Sentry from '@sentry/react-native';

// Your App component here

export default Sentry.wrap(App);

6

验证配置

¥Verify the configuration

创建应用的新版本并验证它是否正确上传源映射。你可能想在应用中添加一个按钮来测试它是否正常工作以及源映射是否按预期连接,例如:

¥Create a new release build of your app and verify that it uploads source maps correctly. You may want to add a button in your app to test that it is working and sourcemaps are wired up as expected, for example:

import { Button } from 'react-native';

// Inside some component
<Button title="Press me" onPress={() => { throw new Error('Hello, again, Sentry!'); }}/>

与 Expo 路由一起使用

¥Usage with Expo Router

如果你的应用使用 Expo 路由,那么你可以将 Sentry 配置为自动捕获当前路由并将其与错误报告一起传递。要进行此设置,请在 根布局路由 中配置 Sentry 并添加路由工具。

¥If your app uses Expo Router, then you can configure Sentry to automatically capture the current route and pass it along with your error reports. To set this up, configure Sentry in the Root Layout route and add routing instrumentation.

Example configuration that instruments Sentry for Expo Router
app/_layout.tsx
import { Slot, useNavigationContainerRef } from 'expo-router';
import React from 'react';
import * as Sentry from '@sentry/react-native';
import { isRunningInExpoGo } from 'expo';

// Construct a new instrumentation instance. This is needed to communicate between the integration and React
const routingInstrumentation = new Sentry.ReactNavigationInstrumentation();

Sentry.init({
  dsn: 'YOUR DSN HERE',
  debug: true, // If `true`, Sentry will try to print out useful debugging information if something goes wrong with sending the event. Set it to `false` in production
  integrations: [
    new Sentry.ReactNativeTracing({
      // Pass instrumentation to be used as `routingInstrumentation`
      routingInstrumentation,
      enableNativeFramesTracking: !isRunningInExpoGo(),
      // ...
    }),
  ],
});

function RootLayout() {
  // Capture the NavigationContainer ref and register it with the instrumentation.
  const ref = useNavigationContainerRef();

  React.useEffect(() => {
    if (ref) {
      routingInstrumentation.registerNavigationContainer(ref);
    }
  }, [ref]);

  return <Slot />;
}

// Wrap the Root Layout route component with `Sentry.wrap` to capture gesture info and profiling data.
export default Sentry.wrap(RootLayout);

与 EAS 构建一起使用

¥Usage with EAS Build

确保在你的构建环境中设置了 SENTRY_AUTH_TOKEN,Sentry 会自动为你上传源映射。如果你在应用配置中使用环境变量而不是属性,请确保也设置了这些变量。

¥Ensure that SENTRY_AUTH_TOKEN is set in your build environment, and Sentry will automatically upload source maps for you. If you use environment variables rather than properties in your app config, ensure that those are set as well.

使用上述说明,在使用 EAS Build 时无需进行任何额外工作即可将 Sentry 集成到你的项目中。

¥Using the above instructions, no additional work is needed to integrate Sentry into your project when using EAS Build.

与 EAS 更新一起使用

¥Usage with EAS Update

运行 eas update 后,将源映射上传到 Sentry:

¥After running eas update, upload the source maps to Sentry:

Terminal
# Pass in the `dist` directory generated by `eas update` to the upload script
npx sentry-expo-upload-sourcemaps dist

就是这样!现在,你的更新错误将在 Sentry 中正确地用符号表示。

¥That's it! Errors for your updates will now be properly symbolicated in Sentry.

Do you want to publish an update and the sourcemaps in one command?

你可以将命令与 && 链接在一起,一步发布更新并上传源映射:

¥You can chain the commands together with && to publish an update and upload the sourcemaps in one step:

Terminal
eas update --branch <branch> && npx sentry-expo-upload-sourcemaps dist

sentry-expo 已合并到 @sentry/react-native 中,现已弃用。我们建议升级到 SDK 50 以使用 @sentry/react-native 以获得最佳体验。如果你已经在使用 sentry-expo了解如何迁移

¥sentry-expo has been merged into @sentry/react-native and is now deprecated. We recommend upgrading to SDK 50 to use @sentry/react-native for the best experience. If you're already using sentry-expo, learn how to migrate.

1

注册 Sentry 账户并创建项目

¥Sign up for a Sentry account and create a project

在获得错误的实时更新并使你的应用总体上令人难以置信之前,你需要确保你已经创建了一个 Sentry 项目。具体做法如下:

¥Before getting real-time updates on errors and making your app generally incredible, you'll need to make sure you have created a Sentry project. Here's how to do that:

1.1

注册 Sentry(免费),然后在仪表板中创建一个项目。记下你的组织名称、项目名称和 DSN,因为稍后你将需要它们:

¥Sign up for Sentry (it's free), and create a project in your Dashboard. Take note of your organization slug, project name, and DSN as you'll need them later:

  • 组织 slug 可在“组织设置”选项卡中找到

    ¥organization slug is available in your Organization settings tab

  • 项目名称可在项目的“设置”>“项目”选项卡中找到(在列表中找到它)

    ¥project name is available in your project's Settings > Projects tab (find it in the list)

  • DSN 可在项目的设置 > 项目 > 项目名称 > 客户端密钥 (DSN) 选项卡中找到。

    ¥DSN is available in your project's Settings > Projects > Project name > Client Keys (DSN) tab.

1.2

转到 Sentry API 部分,并创建一个身份验证令牌。令牌需要范围:org:readproject:releasesproject:write。拯救他们。

¥Go to the Sentry API section, and create an auth token. The token requires the scopes: org:read, project:releases, and project:write. Save them.

一旦你拥有了这些:组织名称、项目名称、DSN 和身份验证令牌,一切就绪!

¥Once you have each of these: organization slug, project name, DSN, and auth token, you're all set!

2

安装

¥Installation

在你的项目目录中,运行:

¥In your project directory, run:

Terminal
npx expo install sentry-expo

sentry-expo 还需要一些额外的 Expo 模块包。要安装它们,请运行:

¥sentry-expo also requires some additional Expo module packages. To install them, run:

Terminal
npx expo install expo-application expo-constants expo-device @sentry/react-native

3

代码

¥Code

初始化

¥Initialization

将以下内容添加到应用的主文件(例如 App.js)中:

¥Add the following to your app's main file such as App.js:

import * as Sentry from 'sentry-expo';

Sentry.init({
  dsn: 'YOUR DSN HERE',
  enableInExpoDevelopment: true,
  debug: true, // If `true`, Sentry will try to print out useful debugging information if something goes wrong with sending the event. Set it to `false` in production
});

用法

¥Usage

根据你所在的平台(移动或 Web),使用以下方法访问任何 @sentry/* 方法以进行检测、性能、捕获异常等:

¥Depending on which platform you are on (mobile or web), use the following methods to access any @sentry/* methods for instrumentation, performance, capturing exceptions and so on:

  • 对于 React Native,使用 Sentry.Native.* 访问任何 @sentry/react-native 导出

    ¥For React Native, access any @sentry/react-native exports with Sentry.Native.*

  • 对于网络,使用 Sentry.Browser.* 访问任何 @sentry/browser 导出

    ¥For web, access any @sentry/browser exports with Sentry.Browser.*

// Access any @sentry/react-native exports via:
// Sentry.Native.*

// Access any @sentry/browser exports via:
// Sentry.Browser.*

// The following example uses `captureException()` from Sentry.Native.* to capture errors:
try {
  // your code
} catch (error) {
  Sentry.Native.captureException(error);
}

4

应用配置

¥App configuration

配置 sentry-expo 是通过 应用配置 中的配置插件完成的。

¥Configuring sentry-expo is done through the config plugin in your app config.

Are you using this library in a bare React Native app?

如果你使用的是裸 React Native 应用,则不应在应用配置中使用 plugins 属性。相反,运行 yarn sentry-wizard -i reactNative -p ios android 来配置你的原生项目。此 sentry-wizard 命令将向项目的根文件(通常是 App.js)添加额外的导入语句和 Sentry.init,如下所示。请确保将其删除,但保留 sentry-expo 导入和原始 Sentry.init 调用。

¥If you are in a bare React Native app, you should not use the plugins property in app config. Instead, run yarn sentry-wizard -i reactNative -p ios android to configure your native projects. This sentry-wizard command will add an extra import statement and Sentry.init to your project's root file (usually App.js) as shown below. Make sure you remove it, however, keep the sentry-expo import and original Sentry.init call.

import * as Sentry from '@sentry/react-native';

Sentry.init({
  dsn: 'YOUR DSN',
});

配置 postPublish 钩子

¥Configure a postPublish hook

expo.hooks 属性添加到项目的 app.json 或 app.config.js 文件中:

¥Add expo.hooks property to your project's app.json or app.config.js file:

app.json
{
  "expo": {
    %%placeholder-start%%...%%placeholder-end%%
    "hooks": {
      "postPublish": [
        {
          "file": "sentry-expo/upload-sourcemaps",
          "config": {
            "organization": "sentry org slug, or use the `SENTRY_ORG` environment variable",
            "project": "sentry project name, or use the `SENTRY_PROJECT` environment variable"
          }
        }
      ]
    }
  }
}

要将源地图上传到 Sentry,你必须创建 Sentry 身份验证令牌。创建 Sentry 身份验证令牌 在此处的账户设置中 后,你可以通过 EAS 构建 中的 SENTRY_AUTH_TOKEN 环境变量配置此令牌。

¥To upload the source map to Sentry, you must create a Sentry auth token. After creating your Sentry auth token in your account's settings here, you can configure this token through the SENTRY_AUTH_TOKEN environment variable in EAS Build.

Sentry 身份验证令牌应安全存储。不要将其提交到公共存储库,并像对待任何其他敏感 API 密钥一样对待它。

除了身份验证令牌之外,你还可以通过环境变量配置以下选项:

¥Besides the auth token, you can also configure the following options through environment variables:

  • 组织 → SENTRY_ORG

    ¥organization → SENTRY_ORG

  • 项目 → SENTRY_PROJECT

    ¥project → SENTRY_PROJECT

Additional configuration options

除了上面必需的配置字段之外,你还可以提供以下可选字段:

¥In addition to the required config fields above, you can also provide these optional fields:

  • setCommits:布尔值,指示是否告知 Sentry 哪些提交与新版本关联。这使得 Sentry 能够查明哪些提交可能导致了问题。

    ¥setCommits: boolean value indicating whether or not to tell Sentry about which commits are associated with a new release. This allows Sentry to pinpoint which commits likely caused an issue.

  • deployEnv:表示部署环境的字符串。这将自动向已 promise 正在部署的版本的 Sentry 用户发送一封电子邮件。

    ¥deployEnv: string indicating the deploy environment. This will automatically send an email to Sentry users who have committed to the release that is being deployed.

  • distribution:为你的发行版提供的名称/值(你可以将其视为子发行版)。Expo 默认使用 app.json 中的 version。如果你提供自定义 distribution,则必须在调用 Sentry.init() 时将相同的值传递给 dist,否则你将不会在错误报告中看到堆栈跟踪。

    ¥distribution: The name/value to give your distribution (you can think of this as a sub-release). Expo defaults to using your version from app.json. If you provide a custom distribution, you must pass the same value to dist in your call to Sentry.init(), otherwise you will not see stacktraces in your error reports.

  • release:你想要为版本指定的名称(例如 release-feature-ABC)。这默认为 JS 包的唯一 revisionId。如果你提供自定义 release,则必须将相同的 release 值传递给 Sentry.init(),否则你将不会在错误报告中看到堆栈跟踪。

    ¥release: The name you'd like to give your release (for example, release-feature-ABC). This defaults to a unique revisionId of your JS bundle. If you provide a custom release, you must pass in the same release value to Sentry.init(), otherwise you will not see stacktraces in your error reports.

  • url:你的 Sentry URL,仅在自托管 Sentry 时才需要。

    ¥url: your Sentry URL, only necessary when self-hosting Sentry.

如果你愿意,你还可以在配置中使用环境变量:

¥You can also use environment variables for your config, if you prefer:

  • setCommits → SENTRY_SET_COMMITS

  • 部署环境 → SENTRY_DEPLOY_ENV

    ¥deployEnv → SENTRY_DEPLOY_ENV

  • 分布 → SENTRY_DIST

    ¥distribution → SENTRY_DIST

  • 发布 → SENTRY_RELEASE

    ¥release → SENTRY_RELEASE

  • 网址 → SENTRY_URL

    ¥url → SENTRY_URL

添加配置插件

¥Add the Config Plugin

将以下内容添加到项目的 app.json 或 app.config.js 文件中:

¥Add the following to your project's app.json or app.config.js file:

app.json
{
  "expo": {
    "plugins": ["sentry-expo"]
    %%placeholder-start%%... %%placeholder-end%%
  }
}

源地图

¥Source maps

postPublish 钩子到位后,现在你所需要做的就是运行 expo-cli publish,源映射将自动上传。每次你点击发布时,我们都会根据你在 app.json 中指定的版本和我们后端的发布 ID,自动为 Sentry 分配一个唯一的发布版本 - 这意味着,如果你忘记更新版本但点击发布,你将 仍然可以获得独特的 Sentry 版本。

¥With the postPublish hook in place, now all you need to do is run expo-cli publish and the source maps will be uploaded automatically. We automatically assign a unique release version for Sentry each time you hit publish, based on the version you specify in app.json and a release id on our backend -- this means that if you forget to update the version but hit publish, you will still get a unique Sentry release.

在构建时上传源映射

¥Uploading source maps at build time

使用 expo-updates,Android 和 iOS 应用的发布版本都将在构建时从 JavaScript 源创建并嵌入新的更新。此新更新不会自动发布,并且仅存在于与其打包在一起的二进制文件中。由于它尚未发布,因此源映射不会像运行 expo-cli publish 时那样以通常的方式上传(实际上,我们依靠 Sentry 的原生脚本来处理该问题)。因此,你需要注意一些额外的事情:

¥With expo-updates, release builds of both Android and iOS apps will create and embed a new update from your JavaScript source at build-time. This new update will not be published automatically and will exist only in the binary with which it was bundled. Since it isn't published, the source maps aren't uploaded in the usual way like they are when you run expo-cli publish (actually, we are relying on Sentry's native scripts to handle that). Because of this you have some extra things to be aware of:

  • 你的 release 将自动设置为 Sentry 的预期值 - ${bundleIdentifier}@${version}+${buildNumber} (iOS) 或 ${androidPackage}@${version}+${versionCode} (Android)。

    ¥Your release will automatically be set to Sentry's expected value- ${bundleIdentifier}@${version}+${buildNumber} (iOS) or ${androidPackage}@${version}+${versionCode} (Android).

  • 你的 dist 将自动设置为 Sentry 的预期值:${buildNumber} (iOS) 或 ${versionCode} (Android)。

    ¥Your dist will automatically be set to Sentry's expected value: ${buildNumber} (iOS) or ${versionCode} (Android).

  • 构建时源映射的配置来自 android/sentry.properties 和 ios/sentry.properties 文件。欲了解更多信息,请参阅 Sentry 的文档。仅裸项目 Sentry-expo 配置插件会以其他方式处理它 需要手动配置。

    ¥The configuration for build time source maps comes from the android/sentry.properties and ios/sentry.properties files. For more information, see Sentry's documentation. Manual configuration is only required for bare projects, the sentry-expo config plugin handles it otherwise.

  • 无论是否使用裸工作流程,项目的 expo publishnpx expo export 的配置都是通过 app.json 完成的。

    ¥Configuration for expo publish and npx expo export for projects is done via app.json, whether using bare workflow or not.

跳过或错误配置其中任何一个都可能导致无效的源映射,并且你不会在错误中看到人类可读的堆栈跟踪。

¥Skipping or misconfiguring either of these can lead to invalid source maps, and you won't see human-readable stacktraces in your errors.

上传源地图以进行更新

¥Uploading source maps for updates

如果你使用 EAS 更新,或者如果你自行托管更新(这意味着你手动运行 npx expo export),则需要执行以下步骤将更新的源映射上传到 Sentry:

¥If you're using EAS Update, or if you're self-hosting your updates (this means you run npx expo export manually), you need to take the following steps to upload the source maps for your update to Sentry:

  • 运行 eas update。这将在项目根目录中生成一个 dist 文件夹,其中包含 JavaScript 包和源映射。该命令还将输出我们下一步需要的 '安卓更新 ID' 和 'iOS 更新 ID'。

    ¥Run eas update. This will generate a dist folder in your project root, which contains your JavaScript bundles and source maps. This command will also output the 'Android update ID' and 'iOS update ID' that we'll need in the next step.

  • 复制或重命名 dist/bundles 文件夹中的包名称以匹配 index.android.bundle (Android) 或 main.jsbundle (iOS)。

    ¥Copy or rename the bundle names in the dist/bundles folder to match index.android.bundle (Android) or main.jsbundle (iOS).

  • 接下来,你可以使用 Sentry CLI 上传包和源映射:

    ¥Next, you can use the Sentry CLI to upload your bundles and source maps:

    • release name 应设置为 ${bundleIdentifier}@${version}+${buildNumber} (iOS) 或 ${androidPackage}@${version}+${versionCode} (Android),例如 com.domain.myapp@1.0.0+1

      ¥release name should be set to ${bundleIdentifier}@${version}+${buildNumber} (iOS) or ${androidPackage}@${version}+${versionCode} (Android), so for example com.domain.myapp@1.0.0+1.

    • dist 应设置为 eas update 生成的更新 ID。

      ¥dist should be set to the Update ID that eas update generated.

Terminal
node_modules/@sentry/cli/bin/sentry-cli releases \
files <release name> \ upload-sourcemaps \ --dist <Android Update ID> \ --rewrite \ dist/bundles/index.android.bundle dist/bundles/android-<hash>.map
Terminal
node_modules/@sentry/cli/bin/sentry-cli releases \
files <release name> \ upload-sourcemaps \ --dist <iOS Update ID> \ --rewrite \ dist/bundles/main.jsbundle dist/bundles/ios-<hash>.map

有关详细信息,请参阅 Sentry 的 上传包和源映射的说明

¥For more information, see Sentry's instructions for uploading the bundle and source maps.

上述步骤在 Sentry 上定义了一个新的 'dist',与你的完整应用构建处于同一版本下,并将源映射与这个新的 dist 相关联。如果要自定义此行为,可以在代码中初始化 Sentry 时传入自己的 releasedist 值。例如:

¥The steps above define a new 'dist' on Sentry, under the same release as your full app build, and associate the source maps with this new dist. If you want to customize this behavior, you can pass in your own values for release and dist when you initialize Sentry in your code. For example:

import * as Sentry from 'sentry-expo';
import * as Updates from 'expo-updates';

Sentry.init({
  dsn: 'YOUR DSN',
  release: 'my release name',
  dist: 'my dist',
});

这些值应与你上传源映射时传递给 sentry-cli 的值匹配。

¥These values should match the values you pass to the sentry-cli when uploading your source maps.

测试 Sentry

¥Testing Sentry

在为应用构建测试时,你希望断言正确的流量跟踪或错误正在发送到 Sentry,但没有真正将其发送到 Sentry 服务器。这样,你就不会在测试运行和其他 CI 操作期间用虚假报告淹没 Sentry。

¥When building tests for your application, you want to assert that the right flow-tracking or error is being sent to Sentry, but without really sending it to Sentry servers. This way you won't swamp Sentry with false reports during test running and other CI operations.

sentry-testkit 使 Sentry 能够在你的应用中原生工作,并且通过覆盖默认的 Sentry 传输机制,报告不会真正发送,而是本地记录到内存中。通过这种方式,你可以稍后获取记录的报告以供你自己使用、验证或你在本地开发/测试环境中可能拥有的任何其他用途。

¥sentry-testkit enables Sentry to work natively in your application, and by overriding the default Sentry transport mechanism, the report is not really sent but rather logged locally into memory. In this way, the logged reports can be fetched later for your own usage, verification, or any other use you may have in your local developing/testing environment.

有关如何开始的更多信息,请参阅 sentry-testkit 文档

¥For more information on how to get started, see sentry-testkit documentation.

如果你使用的是 jest,请确保将 @sentry/.*sentry-expo 添加到 transformIgnorePatterns 中。

¥If you're using jest, make sure to add @sentry/.* and sentry-expo to your transformIgnorePatterns.

错误报告语义

¥Error reporting semantics

为了确保可靠地报告错误,Sentry 推迟将数据报告给后端,直到你下次在发生致命错误后加载应用时,而不是在捕获异常时尝试报告数据。它将堆栈跟踪和其他元数据保存到 AsyncStorage 并在应用启动时立即发送。

¥To ensure that errors are reported reliably, Sentry defers reporting the data to their backend until the next time you load the app after a fatal error rather than trying to report it upon catching the exception. It saves the stacktrace and other metadata to AsyncStorage and sends it immediately when the app starts.

开发中默认禁用

¥Disabled by default in dev

除非设置了 enableInExpoDevelopment: true,否则所有开发/本地错误都将被忽略,只有应用版本才会向 Sentry 报告错误。你可以调用诸如 Sentry.Native.captureException(new Error('Oops!')) 之类的方法,但这些方法将是无操作的。

¥Unless enableInExpoDevelopment: true is set, all your dev/local errors will be ignored and only app releases will report errors to Sentry. You can call methods like Sentry.Native.captureException(new Error('Oops!')) but these methods will be no-op.

故障排除

¥Troubleshooting

I'm seeing error: project not found in my build logs

此错误是由构建期间尝试上传源映射的脚本引起的。

¥This error is caused by the script that tries to upload source maps during build.

确保 organizationprojectauthToken 属性设置正确。

¥Make sure your organization, project and authToken properties are set correctly.

expo-dev-client transactions never finish

此错误是由 HTTP 请求跟踪引起的,该跟踪会为开发服务器创建日志请求 (Starting 'http.client' span on transaction...) 的跨度。要解决此问题,请通过添加以下代码片段来停止创建跨度:

¥This error is caused by the HTTP request tracking, which creates spans for log requests (Starting 'http.client' span on transaction...) to the development server. To fix this, stop creating spans by adding the following code snippet:

import * as Sentry from 'sentry-expo';
import Constants from 'expo-constants';

Sentry.init({
  tracesSampleRate: 1.0,
  integrations: [
    new Sentry.Native.ReactNativeTracing({
      shouldCreateSpanForRequest: url => {
        return !__DEV__ || !url.startsWith(`http://${Constants.expoConfig.hostUri}/logs`);
      },
    }),
  ],
});

了解有关 Sentry 的更多信息

¥Learn more about Sentry

Sentry 的作用不仅仅是捕获致命错误,还可以从其 JavaScript 使用 文档中了解有关如何使用 Sentry 的更多信息。

¥Sentry does more than just catch fatal errors, learn more about how to use Sentry from their JavaScript usage documentation.