sentry-react-native-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Sentry React Native SDK

Sentry React Native SDK

Opinionated wizard that scans your React Native or Expo project and guides you through complete Sentry setup — error monitoring, tracing, profiling, session replay, logging, and more.
这是一个个性化的向导工具,会扫描你的React Native或Expo项目,并引导你完成Sentry的完整设置——包括错误监控、链路追踪、性能分析、会话重放、日志记录等功能。

Invoke This Skill When

何时调用此技能

  • User asks to "add Sentry to React Native" or "set up Sentry" in an RN or Expo app
  • User wants error monitoring, tracing, profiling, session replay, or logging in React Native
  • User mentions
    @sentry/react-native
    , mobile error tracking, or Sentry for Expo
  • User wants to monitor native crashes, ANRs, or app hangs on iOS/Android
Note: SDK versions and APIs below reflect current Sentry docs at time of writing (
@sentry/react-native
≥6.0.0, minimum recommended ≥8.0.0). Always verify against docs.sentry.io/platforms/react-native/ before implementing.

  • 用户要求在React Native或Expo应用中“添加Sentry”或“设置Sentry”
  • 用户希望在React Native中实现错误监控、链路追踪、性能分析、会话重放或日志记录
  • 用户提到
    @sentry/react-native
    、移动端错误追踪或Expo版Sentry
  • 用户希望监控iOS/Android上的原生崩溃、ANR(应用无响应)或应用卡顿
注意: 以下SDK版本和API基于编写时的Sentry官方文档(
@sentry/react-native
≥6.0.0,推荐最低版本≥8.0.0)。 实施前请务必对照Sentry官方文档进行验证。

Phase 1: Detect

第一阶段:项目检测

Run these commands to understand the project before making any recommendations:
bash
undefined
在给出任何建议前,先运行以下命令了解项目情况:
bash
undefined

Detect project type and existing Sentry

检测项目类型和已有的Sentry配置

cat package.json | grep -E '"(react-native|expo|@expo|@sentry/react-native|sentry-expo)"'
cat package.json | grep -E '"(react-native|expo|@expo|@sentry/react-native|sentry-expo)"'

Distinguish Expo managed vs bare vs vanilla RN

区分Expo托管式、裸工程或原生React Native

ls app.json app.config.js app.config.ts 2>/dev/null cat app.json 2>/dev/null | python3 -c "import sys,json; d=json.load(sys.stdin); print('Expo managed' if 'expo' in d else 'Bare/Vanilla')" 2>/dev/null
ls app.json app.config.js app.config.ts 2>/dev/null cat app.json 2>/dev/null | python3 -c "import sys,json; d=json.load(sys.stdin); print('Expo托管式' if 'expo' in d else '裸工程/原生RN')" 2>/dev/null

Check Expo SDK version (important: Expo SDK 50+ required for @sentry/react-native)

检查Expo SDK版本(重要:Expo SDK 50+才能使用@sentry/react-native)

cat package.json | grep '"expo"'
cat package.json | grep '"expo"'

Detect navigation library

检测导航库

grep -E '"(@react-navigation/native|react-native-navigation)"' package.json
grep -E '"(@react-navigation/native|react-native-navigation)"' package.json

Detect state management (Redux → breadcrumb integration available)

检测状态管理库(Redux可集成面包屑功能)

grep -E '"(redux|@reduxjs/toolkit|zustand|mobx)"' package.json
grep -E '"(redux|@reduxjs/toolkit|zustand|mobx)"' package.json

Check for existing Sentry initialization

检查是否已初始化Sentry

grep -r "Sentry.init" src/ app/ App.tsx App.js _layout.tsx 2>/dev/null | head -5
grep -r "Sentry.init" src/ app/ App.tsx App.js _layout.tsx 2>/dev/null | head -5

Detect Hermes (affects source map handling)

检测Hermes引擎(影响source map处理)

cat android/app/build.gradle 2>/dev/null | grep -i hermes cat ios/Podfile 2>/dev/null | grep -i hermes
cat android/app/build.gradle 2>/dev/null | grep -i hermes cat ios/Podfile 2>/dev/null | grep -i hermes

Detect Expo Router

检测Expo Router

ls app/_layout.tsx app/_layout.js 2>/dev/null
ls app/_layout.tsx app/_layout.js 2>/dev/null

Detect backend for cross-link

检测后端项目用于跨链路关联

ls backend/ server/ api/ 2>/dev/null find . -maxdepth 3 ( -name "go.mod" -o -name "requirements.txt" -o -name "Gemfile" -o -name "package.json" ) 2>/dev/null | grep -v node_modules | head -10

**What to determine:**

| Question | Impact |
|----------|--------|
| `expo` in `package.json`? | Expo path (config plugin + `getSentryExpoConfig`) vs bare/vanilla RN path |
| Expo SDK ≥50? | `@sentry/react-native` directly; older = `sentry-expo` (legacy, do not use) |
| `app.json` has `"expo"` key? | Managed Expo — wizard is simplest; config plugin handles all native config |
| `app/_layout.tsx` present? | Expo Router project — init goes in `_layout.tsx` |
| `@sentry/react-native` already in `package.json`? | Skip install, jump to feature config |
| `@react-navigation/native` present? | Recommend `reactNavigationIntegration` for screen tracking |
| `react-native-navigation` present? | Recommend `reactNativeNavigationIntegration` (Wix) |
| Backend directory detected? | Trigger Phase 4 cross-link |

---
ls backend/ server/ api/ 2>/dev/null find . -maxdepth 3 ( -name "go.mod" -o -name "requirements.txt" -o -name "Gemfile" -o -name "package.json" ) 2>/dev/null | grep -v node_modules | head -10

**需要确定的信息:**

| 问题 | 影响 |
|----------|--------|
| `package.json`中是否包含`expo`? | 决定使用Expo专属路径(配置插件+`getSentryExpoConfig`)还是裸工程/原生RN路径 |
| Expo SDK版本≥50? | 直接使用`@sentry/react-native`;旧版本需使用`sentry-expo`(已废弃,不推荐) |
| `app.json`中是否有`"expo"`字段? | Expo托管式项目——向导工具最简便,配置插件会处理所有原生配置 |
| 是否存在`app/_layout.tsx`? | Expo Router项目——初始化代码需放在`_layout.tsx`中 |
| `package.json`中已包含`@sentry/react-native`? | 跳过安装步骤,直接进入功能配置 |
| 是否存在`@react-navigation/native`? | 推荐使用`reactNavigationIntegration`实现页面追踪 |
| 是否存在`react-native-navigation`? | 推荐使用`reactNativeNavigationIntegration`(Wix版本) |
| 检测到后端目录? | 触发第四阶段的跨链路关联 |

---

Phase 2: Recommend

第二阶段:方案推荐

Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:
Recommended (core coverage — always set up these):
  • Error Monitoring — captures JS exceptions, native crashes (iOS + Android), ANRs, and app hangs
  • Tracing — mobile performance is critical; auto-instruments navigation, app start, network requests
  • Session Replay — mobile replay captures screenshots and touch events for debugging user issues
Optional (enhanced observability):
  • Profiling — CPU profiling on iOS (JS profiling cross-platform); low overhead in production
  • Logging — structured logs via
    Sentry.logger.*
    ; links to traces for full context
  • User Feedback — collect user-submitted bug reports directly from your app
Recommendation logic:
FeatureRecommend when...
Error MonitoringAlways — non-negotiable baseline for any mobile app
TracingAlways for mobile — app start, navigation, and network latency matter
Session ReplayUser-facing production app; debug user-reported issues visually
ProfilingPerformance-sensitive screens, startup time concerns, or production perf investigations
LoggingApp uses structured logging, or you want log-to-trace correlation in Sentry
User FeedbackBeta or customer-facing app where you want user-submitted bug reports
Propose: "For your [Expo managed / bare RN] app, I recommend setting up Error Monitoring + Tracing + Session Replay. Want me to also add Profiling and Logging?"

根据检测结果给出具体建议,避免开放式问题,直接给出方案:
推荐核心功能(必须配置):
  • 错误监控 —— 捕获JS异常、原生崩溃(iOS + Android)、ANR和应用卡顿
  • 链路追踪 —— 移动端性能至关重要;自动埋点导航、应用启动、网络请求
  • 会话重放 —— 移动端重放可捕获截图和触摸事件,用于调试用户问题
可选增强功能:
  • 性能分析 —— iOS支持CPU分析(JS分析跨平台);生产环境低开销
  • 日志记录 —— 通过
    Sentry.logger.*
    实现结构化日志;与链路追踪关联获取完整上下文
  • 用户反馈 —— 直接从应用中收集用户提交的Bug报告
推荐逻辑:
功能推荐场景
错误监控始终启用 —— 任何移动端应用的必备基础功能
链路追踪移动端必选 —— 应用启动、导航和网络延迟对体验影响重大
会话重放面向用户的生产环境应用;需要可视化调试用户反馈的问题
性能分析对性能敏感的页面、启动时间优化需求,或生产环境性能排查
日志记录应用使用结构化日志,或需要在Sentry中实现日志与链路的关联
用户反馈Beta版或面向客户的应用,需要收集用户提交的Bug报告
建议话术:“针对你的[Expo托管式 / 裸RN]应用,我建议配置错误监控 + 链路追踪 + 会话重放。是否需要同时添加性能分析和日志记录功能?”

Phase 3: Guide

第三阶段:分步引导

Determine Your Setup Path

确定设置路径

Project typeRecommended setupComplexity
Expo managed (SDK 50+)Wizard CLI or manual with config pluginLow — wizard does everything
Expo bare (SDK 50+)Wizard CLI recommendedMedium — handles iOS/Android config
Vanilla React Native (0.69+)Wizard CLI recommendedMedium — handles Xcode + Gradle
Expo SDK <50Use
sentry-expo
(legacy)
See legacy docs

项目类型推荐设置方式复杂度
Expo托管式(SDK 50+)向导CLI或手动配置插件低 —— 向导工具自动完成所有操作
Expo裸工程(SDK 50+)推荐使用向导CLI中 —— 处理iOS/Android配置
原生React Native(0.69+)推荐使用向导CLI中 —— 处理Xcode + Gradle配置
Expo SDK <50使用
sentry-expo
(已废弃)
参考旧版文档

Path A: Wizard CLI (Recommended for all project types)

路径A:向导CLI(所有项目类型推荐)

Run the wizard — it walks you through login, org/project selection, and auth token setup interactively. It then handles installation, native config, source map upload, and initial
Sentry.init()
:
bash
npx @sentry/wizard@latest -i reactNative
What the wizard creates/modifies:
FileActionPurpose
package.json
Installs
@sentry/react-native
Core SDK
metro.config.js
Adds
@sentry/react-native/metro
serializer
Source map generation
app.json
Adds
@sentry/react-native/expo
plugin (Expo only)
Config plugin for native builds
App.tsx
/
_layout.tsx
Adds
Sentry.init()
and
Sentry.wrap()
SDK initialization
ios/sentry.properties
Stores org/project/tokeniOS source map + dSYM upload
android/sentry.properties
Stores org/project/tokenAndroid source map upload
android/app/build.gradle
Adds Sentry Gradle pluginAndroid source maps + proguard
ios/[AppName].xcodeproj
Wraps "Bundle RN" build phase + adds dSYM uploadiOS symbol upload
.env.local
SENTRY_AUTH_TOKEN
Auth token (add to
.gitignore
)
After the wizard runs, skip to Verification.

运行以下向导命令——它会引导你完成登录、组织/项目选择和授权令牌设置。之后会自动处理安装、原生配置、source map上传和初始
Sentry.init()
bash
npx @sentry/wizard@latest -i reactNative
向导会创建/修改的文件:
文件操作用途
package.json
安装
@sentry/react-native
核心SDK
metro.config.js
添加
@sentry/react-native/metro
序列化器
生成source map
app.json
添加
@sentry/react-native/expo
插件(仅Expo)
原生构建的配置插件
App.tsx
/
_layout.tsx
添加
Sentry.init()
Sentry.wrap()
SDK初始化
ios/sentry.properties
存储组织/项目/令牌iOS source map + dSYM上传
android/sentry.properties
存储组织/项目/令牌Android source map上传
android/app/build.gradle
添加Sentry Gradle插件Android source map + ProGuard配置
ios/[AppName].xcodeproj
替换“Bundle RN”构建阶段并添加dSYM上传iOS符号上传
.env.local
添加
SENTRY_AUTH_TOKEN
授权令牌(需加入
.gitignore
向导运行完成后,跳至验证环节

Path B: Manual — Expo Managed (SDK 50+)

路径B:手动配置——Expo托管式(SDK 50+)

Step 1 — Install
bash
npx expo install @sentry/react-native
Step 2 —
metro.config.js
javascript
const { getSentryExpoConfig } = require("@sentry/react-native/metro");
const config = getSentryExpoConfig(__dirname);
module.exports = config;
If
metro.config.js
doesn't exist yet:
bash
npx expo customize metro.config.js
步骤1 —— 安装SDK
bash
npx expo install @sentry/react-native
步骤2 —— 配置
metro.config.js
javascript
const { getSentryExpoConfig } = require("@sentry/react-native/metro");
const config = getSentryExpoConfig(__dirname);
module.exports = config;
如果
metro.config.js
尚未存在:
bash
npx expo customize metro.config.js

Then replace contents with the above

然后将文件内容替换为上述代码


**Step 3 — `app.json` — Add Expo config plugin**

```json
{
  "expo": {
    "plugins": [
      [
        "@sentry/react-native/expo",
        {
          "url": "https://sentry.io/",
          "project": "YOUR_PROJECT_SLUG",
          "organization": "YOUR_ORG_SLUG"
        }
      ]
    ]
  }
}
Note: Set
SENTRY_AUTH_TOKEN
as an environment variable for native builds — never commit it to version control.
Step 4 — Initialize Sentry
For Expo Router (
app/_layout.tsx
):
typescript
import { Stack, useNavigationContainerRef } from "expo-router";
import { isRunningInExpoGo } from "expo";
import * as Sentry from "@sentry/react-native";
import React from "react";

const navigationIntegration = Sentry.reactNavigationIntegration({
  enableTimeToInitialDisplay: !isRunningInExpoGo(), // disabled in Expo Go
});

Sentry.init({
  dsn: process.env.EXPO_PUBLIC_SENTRY_DSN ?? "YOUR_SENTRY_DSN",
  sendDefaultPii: true,

  // Tracing
  tracesSampleRate: 1.0, // lower to 0.1–0.2 in production

  // Profiling
  profilesSampleRate: 1.0,

  // Session Replay
  replaysOnErrorSampleRate: 1.0,
  replaysSessionSampleRate: 0.1,

  // Logging (SDK ≥7.0.0)
  enableLogs: true,

  // Navigation
  integrations: [
    navigationIntegration,
    Sentry.mobileReplayIntegration(),
  ],

  enableNativeFramesTracking: !isRunningInExpoGo(), // slow/frozen frames

  environment: __DEV__ ? "development" : "production",
});

function RootLayout() {
  const ref = useNavigationContainerRef();

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

  return <Stack />;
}

export default Sentry.wrap(RootLayout);
For standard Expo (
App.tsx
):
typescript
import { NavigationContainer, createNavigationContainerRef } from "@react-navigation/native";
import { isRunningInExpoGo } from "expo";
import * as Sentry from "@sentry/react-native";

const navigationIntegration = Sentry.reactNavigationIntegration({
  enableTimeToInitialDisplay: !isRunningInExpoGo(),
});

Sentry.init({
  dsn: process.env.EXPO_PUBLIC_SENTRY_DSN ?? "YOUR_SENTRY_DSN",
  sendDefaultPii: true,
  tracesSampleRate: 1.0,
  profilesSampleRate: 1.0,
  replaysOnErrorSampleRate: 1.0,
  replaysSessionSampleRate: 0.1,
  enableLogs: true,
  integrations: [
    navigationIntegration,
    Sentry.mobileReplayIntegration(),
  ],
  enableNativeFramesTracking: !isRunningInExpoGo(),
  environment: __DEV__ ? "development" : "production",
});

const navigationRef = createNavigationContainerRef();

function App() {
  return (
    <NavigationContainer
      ref={navigationRef}
      onReady={() => {
        navigationIntegration.registerNavigationContainer(navigationRef);
      }}
    >
      {/* your navigation here */}
    </NavigationContainer>
  );
}

export default Sentry.wrap(App);


**步骤3 —— 配置`app.json`——添加Expo配置插件**

```json
{
  "expo": {
    "plugins": [
      [
        "@sentry/react-native/expo",
        {
          "url": "https://sentry.io/",
          "project": "你的项目标识",
          "organization": "你的组织标识"
        }
      ]
    ]
  }
}
注意: 请将
SENTRY_AUTH_TOKEN
设置为环境变量用于原生构建——切勿提交到版本控制系统。
步骤4 —— 初始化Sentry
对于Expo Router
app/_layout.tsx
):
typescript
import { Stack, useNavigationContainerRef } from "expo-router";
import { isRunningInExpoGo } from "expo";
import * as Sentry from "@sentry/react-native";
import React from "react";

const navigationIntegration = Sentry.reactNavigationIntegration({
  enableTimeToInitialDisplay: !isRunningInExpoGo(), // Expo Go中禁用
});

Sentry.init({
  dsn: process.env.EXPO_PUBLIC_SENTRY_DSN ?? "你的SENTRY_DSN",
  sendDefaultPii: true,

  // 链路追踪
  tracesSampleRate: 1.0, // 生产环境可降低至0.1–0.2

  // 性能分析
  profilesSampleRate: 1.0,

  // 会话重放
  replaysOnErrorSampleRate: 1.0,
  replaysSessionSampleRate: 0.1,

  // 日志记录(SDK ≥7.0.0)
  enableLogs: true,

  // 导航集成
  integrations: [
    navigationIntegration,
    Sentry.mobileReplayIntegration(),
  ],

  enableNativeFramesTracking: !isRunningInExpoGo(), // 慢帧/冻结帧追踪

  environment: __DEV__ ? "development" : "production",
});

function RootLayout() {
  const ref = useNavigationContainerRef();

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

  return <Stack />;
}

export default Sentry.wrap(RootLayout);
对于标准Expo
App.tsx
):
typescript
import { NavigationContainer, createNavigationContainerRef } from "@react-navigation/native";
import { isRunningInExpoGo } from "expo";
import * as Sentry from "@sentry/react-native";

const navigationIntegration = Sentry.reactNavigationIntegration({
  enableTimeToInitialDisplay: !isRunningInExpoGo(),
});

Sentry.init({
  dsn: process.env.EXPO_PUBLIC_SENTRY_DSN ?? "你的SENTRY_DSN",
  sendDefaultPii: true,
  tracesSampleRate: 1.0,
  profilesSampleRate: 1.0,
  replaysOnErrorSampleRate: 1.0,
  replaysSessionSampleRate: 0.1,
  enableLogs: true,
  integrations: [
    navigationIntegration,
    Sentry.mobileReplayIntegration(),
  ],
  enableNativeFramesTracking: !isRunningInExpoGo(),
  environment: __DEV__ ? "development" : "production",
});

const navigationRef = createNavigationContainerRef();

function App() {
  return (
    <NavigationContainer
      ref={navigationRef}
      onReady={() => {
        navigationIntegration.registerNavigationContainer(navigationRef);
      }}
    >
      {/* 你的导航组件 */}
    </NavigationContainer>
  );
}

export default Sentry.wrap(App);

Path C: Manual — Bare React Native (0.69+)

路径C:手动配置——裸React Native(0.69+)

Step 1 — Install
bash
npm install @sentry/react-native --save
cd ios && pod install
Step 2 —
metro.config.js
javascript
const { getDefaultConfig } = require("@react-native/metro-config");
const { withSentryConfig } = require("@sentry/react-native/metro");

const config = getDefaultConfig(__dirname);
module.exports = withSentryConfig(config);
Step 3 — iOS: Modify Xcode build phase
Open
ios/[AppName].xcodeproj
in Xcode. Find the "Bundle React Native code and images" build phase and replace the script content with:
bash
undefined
步骤1 —— 安装SDK
bash
npm install @sentry/react-native --save
cd ios && pod install
步骤2 —— 配置
metro.config.js
javascript
const { getDefaultConfig } = require("@react-native/metro-config");
const { withSentryConfig } = require("@sentry/react-native/metro");

const config = getDefaultConfig(__dirname);
module.exports = withSentryConfig(config);
步骤3 —— iOS:修改Xcode构建阶段
在Xcode中打开
ios/[AppName].xcodeproj
。找到**“Bundle React Native code and images”**构建阶段,替换脚本内容为:
bash
undefined

RN 0.81.1+

RN 0.81.1+

set -e WITH_ENVIRONMENT="../node_modules/react-native/scripts/xcode/with-environment.sh" SENTRY_XCODE="../node_modules/@sentry/react-native/scripts/sentry-xcode.sh" /bin/sh -c "$WITH_ENVIRONMENT $SENTRY_XCODE"

**Step 4 — iOS: Add "Upload Debug Symbols to Sentry" build phase**

Add a new **Run Script** build phase in Xcode (after the bundle phase):

```bash
/bin/sh ../node_modules/@sentry/react-native/scripts/sentry-xcode-debug-files.sh
Step 5 — iOS:
ios/sentry.properties
properties
defaults.url=https://sentry.io/
defaults.org=YOUR_ORG_SLUG
defaults.project=YOUR_PROJECT_SLUG
auth.token=YOUR_ORG_AUTH_TOKEN
Step 6 — Android:
android/app/build.gradle
Add before the
android {}
block:
groovy
apply from: "../../node_modules/@sentry/react-native/sentry.gradle"
Step 7 — Android:
android/sentry.properties
properties
defaults.url=https://sentry.io/
defaults.org=YOUR_ORG_SLUG
defaults.project=YOUR_PROJECT_SLUG
auth.token=YOUR_ORG_AUTH_TOKEN
Step 8 — Initialize Sentry (
App.tsx
or entry point)
typescript
import { NavigationContainer, createNavigationContainerRef } from "@react-navigation/native";
import * as Sentry from "@sentry/react-native";

const navigationIntegration = Sentry.reactNavigationIntegration({
  enableTimeToInitialDisplay: true,
});

Sentry.init({
  dsn: "YOUR_SENTRY_DSN",
  sendDefaultPii: true,
  tracesSampleRate: 1.0,
  profilesSampleRate: 1.0,
  replaysOnErrorSampleRate: 1.0,
  replaysSessionSampleRate: 0.1,
  enableLogs: true,
  integrations: [
    navigationIntegration,
    Sentry.mobileReplayIntegration(),
  ],
  enableNativeFramesTracking: true,
  environment: __DEV__ ? "development" : "production",
});

const navigationRef = createNavigationContainerRef();

function App() {
  return (
    <NavigationContainer
      ref={navigationRef}
      onReady={() => {
        navigationIntegration.registerNavigationContainer(navigationRef);
      }}
    >
      {/* your navigation here */}
    </NavigationContainer>
  );
}

export default Sentry.wrap(App);

set -e WITH_ENVIRONMENT="../node_modules/react-native/scripts/xcode/with-environment.sh" SENTRY_XCODE="../node_modules/@sentry/react-native/scripts/sentry-xcode.sh" /bin/sh -c "$WITH_ENVIRONMENT $SENTRY_XCODE"

**步骤4 —— iOS:添加“Upload Debug Symbols to Sentry”构建阶段**

在Xcode中添加一个新的**Run Script**构建阶段(在Bundle阶段之后):

```bash
/bin/sh ../node_modules/@sentry/react-native/scripts/sentry-xcode-debug-files.sh
步骤5 —— iOS:配置
ios/sentry.properties
properties
defaults.url=https://sentry.io/
defaults.org=你的组织标识
defaults.project=你的项目标识
auth.token=你的组织授权令牌
步骤6 —— Android:配置
android/app/build.gradle
android {}
块之前添加:
groovy
apply from: "../../node_modules/@sentry/react-native/sentry.gradle"
步骤7 —— Android:配置
android/sentry.properties
properties
defaults.url=https://sentry.io/
defaults.org=你的组织标识
defaults.project=你的项目标识
auth.token=你的组织授权令牌
步骤8 —— 初始化Sentry(
App.tsx
或入口文件)
typescript
import { NavigationContainer, createNavigationContainerRef } from "@react-navigation/native";
import * as Sentry from "@sentry/react-native";

const navigationIntegration = Sentry.reactNavigationIntegration({
  enableTimeToInitialDisplay: true,
});

Sentry.init({
  dsn: "你的SENTRY_DSN",
  sendDefaultPii: true,
  tracesSampleRate: 1.0,
  profilesSampleRate: 1.0,
  replaysOnErrorSampleRate: 1.0,
  replaysSessionSampleRate: 0.1,
  enableLogs: true,
  integrations: [
    navigationIntegration,
    Sentry.mobileReplayIntegration(),
  ],
  enableNativeFramesTracking: true,
  environment: __DEV__ ? "development" : "production",
});

const navigationRef = createNavigationContainerRef();

function App() {
  return (
    <NavigationContainer
      ref={navigationRef}
      onReady={() => {
        navigationIntegration.registerNavigationContainer(navigationRef);
      }}
    >
      {/* 你的导航组件 */}
    </NavigationContainer>
  );
}

export default Sentry.wrap(App);

Quick Reference: Full-Featured
Sentry.init()

参考:全功能
Sentry.init()
配置

This is the recommended starting configuration with all features enabled:
typescript
import * as Sentry from "@sentry/react-native";

Sentry.init({
  dsn: "YOUR_SENTRY_DSN",
  sendDefaultPii: true,

  // Tracing — lower to 0.1–0.2 in high-traffic production
  tracesSampleRate: 1.0,

  // Profiling — runs on a subset of traced transactions
  profilesSampleRate: 1.0,

  // Session Replay — always capture on error, sample 10% of all sessions
  replaysOnErrorSampleRate: 1.0,
  replaysSessionSampleRate: 0.1,

  // Logging — enable Sentry.logger.* API
  enableLogs: true,

  // Integrations — mobile replay is opt-in
  integrations: [
    Sentry.mobileReplayIntegration({
      maskAllText: true,   // masks text by default for privacy
      maskAllImages: true,
    }),
  ],

  // Native frames tracking (disable in Expo Go)
  enableNativeFramesTracking: true,

  // Environment
  environment: __DEV__ ? "development" : "production",

  // Release — set from CI or build system
  // release: "my-app@1.0.0+1",
  // dist: "1",
});

// REQUIRED: Wrap root component to capture React render errors
export default Sentry.wrap(App);

以下是推荐的初始配置,包含所有功能:
typescript
import * as Sentry from "@sentry/react-native";

Sentry.init({
  dsn: "你的SENTRY_DSN",
  sendDefaultPii: true,

  // 链路追踪——高流量生产环境可降低至0.1–0.2
  tracesSampleRate: 1.0,

  // 性能分析——对所有追踪的事务进行分析(分析始终是追踪的子集)
  profilesSampleRate: 1.0,

  // 会话重放——捕获所有错误会话,抽样10%的正常会话
  replaysOnErrorSampleRate: 1.0,
  replaysSessionSampleRate: 0.1,

  // 日志记录——启用Sentry.logger.* API
  enableLogs: true,

  // 集成——移动端重放需手动启用
  integrations: [
    Sentry.mobileReplayIntegration({
      maskAllText: true,   // 默认屏蔽文本以保护隐私
      maskAllImages: true,
    }),
  ],

  // 原生帧追踪(Expo Go中禁用)
  enableNativeFramesTracking: true,

  // 环境标识
  environment: __DEV__ ? "development" : "production",

  // 版本号——由CI或构建系统设置
  // release: "my-app@1.0.0+1",
  // dist: "1",
});

// 必须:包裹根组件以捕获React渲染错误
export default Sentry.wrap(App);

Navigation Setup — React Navigation (v5+)

导航配置——React Navigation(v5+)

typescript
import { reactNavigationIntegration } from "@sentry/react-native";
import { NavigationContainer, createNavigationContainerRef } from "@react-navigation/native";

const navigationIntegration = reactNavigationIntegration({
  enableTimeToInitialDisplay: true,   // track TTID per screen
  routeChangeTimeoutMs: 1_000,        // max wait for route change to settle
  ignoreEmptyBackNavigationTransactions: true,
});

// Add to Sentry.init integrations array
Sentry.init({
  integrations: [navigationIntegration],
  // ...
});

// In your component:
const navigationRef = createNavigationContainerRef();

<NavigationContainer
  ref={navigationRef}
  onReady={() => {
    navigationIntegration.registerNavigationContainer(navigationRef);
  }}
>
typescript
import { reactNavigationIntegration } from "@sentry/react-native";
import { NavigationContainer, createNavigationContainerRef } from "@react-navigation/native";

const navigationIntegration = reactNavigationIntegration({
  enableTimeToInitialDisplay: true,   // 追踪每个页面的TTID
  routeChangeTimeoutMs: 1_000,        // 路由变更的最大等待时间
  ignoreEmptyBackNavigationTransactions: true,
});

// 添加到Sentry.init的integrations数组
Sentry.init({
  integrations: [navigationIntegration],
  // ...
});

// 在组件中:
const navigationRef = createNavigationContainerRef();

<NavigationContainer
  ref={navigationRef}
  onReady={() => {
    navigationIntegration.registerNavigationContainer(navigationRef);
  }}
>

Navigation Setup — Wix React Native Navigation

导航配置——Wix React Native Navigation

typescript
import * as Sentry from "@sentry/react-native";
import { Navigation } from "react-native-navigation";

Sentry.init({
  integrations: [Sentry.reactNativeNavigationIntegration({ navigation: Navigation })],
  // ...
});

typescript
import * as Sentry from "@sentry/react-native";
import { Navigation } from "react-native-navigation";

Sentry.init({
  integrations: [Sentry.reactNativeNavigationIntegration({ navigation: Navigation })],
  // ...
});

Wrap Your Root Component

包裹根组件

Always wrap your root component — this enables React error boundaries and ensures crashes at the component tree level are captured:
typescript
export default Sentry.wrap(App);

务必包裹根组件——这会启用React错误边界,确保组件树层面的崩溃被捕获:
typescript
export default Sentry.wrap(App);

For Each Agreed Feature

功能分步配置

Walk through features one at a time. Load the reference file for each, follow its steps, then verify before moving on:
FeatureReferenceLoad when...
Error Monitoring
${SKILL_ROOT}/references/error-monitoring.md
Always (baseline)
Tracing & Performance
${SKILL_ROOT}/references/tracing.md
Always for mobile (app start, navigation, network)
Profiling
${SKILL_ROOT}/references/profiling.md
Performance-sensitive production apps
Session Replay
${SKILL_ROOT}/references/session-replay.md
User-facing apps
Logging
${SKILL_ROOT}/references/logging.md
Structured logging / log-to-trace correlation
User Feedback
${SKILL_ROOT}/references/user-feedback.md
Collecting user-submitted reports
For each feature:
Read ${SKILL_ROOT}/references/<feature>.md
, follow steps exactly, verify it works.

逐个配置已确认的功能。加载每个功能的参考文档,按照步骤操作,完成后再进行验证:
功能参考文档加载时机
错误监控
${SKILL_ROOT}/references/error-monitoring.md
始终加载(基础功能)
链路追踪与性能
${SKILL_ROOT}/references/tracing.md
移动端始终加载(应用启动、导航、网络)
性能分析
${SKILL_ROOT}/references/profiling.md
对性能敏感的生产环境应用
会话重放
${SKILL_ROOT}/references/session-replay.md
面向用户的应用
日志记录
${SKILL_ROOT}/references/logging.md
结构化日志 / 日志与链路关联需求
用户反馈
${SKILL_ROOT}/references/user-feedback.md
需要收集用户提交的报告
对于每个功能:
阅读${SKILL_ROOT}/references/<feature>.md
,严格按照步骤操作,验证功能正常。

Configuration Reference

配置参考

Core
Sentry.init()
Options

核心
Sentry.init()
选项

OptionTypeDefaultPurpose
dsn
string
Required. Project DSN; SDK disabled if empty. Env:
SENTRY_DSN
environment
string
e.g.,
"production"
,
"staging"
. Env:
SENTRY_ENVIRONMENT
release
string
App version, e.g.,
"my-app@1.0.0+42"
. Env:
SENTRY_RELEASE
dist
string
Build number / variant identifier (max 64 chars)
sendDefaultPii
boolean
false
Include PII: IP address, cookies, user data
sampleRate
number
1.0
Error event sampling (0.0–1.0)
maxBreadcrumbs
number
100
Max breadcrumbs per event
attachStacktrace
boolean
true
Auto-attach stack traces to messages
attachScreenshot
boolean
false
Capture screenshot on error (SDK ≥4.11.0)
attachViewHierarchy
boolean
false
Attach JSON view hierarchy as attachment
debug
boolean
false
Verbose SDK output. Never use in production
enabled
boolean
true
Disable SDK entirely (e.g., for testing)
ignoreErrors
string[] | RegExp[]
Drop errors matching these patterns
ignoreTransactions
string[] | RegExp[]
Drop transactions matching these patterns
maxCacheItems
number
30
Max offline-cached envelopes
defaultIntegrations
boolean
true
Set
false
to disable all default integrations
integrations
array | function
Add or filter integrations
选项类型默认值用途
dsn
string
必填。项目DSN;若为空则SDK禁用。环境变量:
SENTRY_DSN
environment
string
例如
"production"
"staging"
。环境变量:
SENTRY_ENVIRONMENT
release
string
应用版本,例如
"my-app@1.0.0+42"
。环境变量:
SENTRY_RELEASE
dist
string
构建编号 / 变体标识(最多64字符)
sendDefaultPii
boolean
false
是否包含个人身份信息:IP地址、Cookie、用户数据
sampleRate
number
1.0
错误事件抽样率(0.0–1.0)
maxBreadcrumbs
number
100
每个事件的最大面包屑数量
attachStacktrace
boolean
true
自动为消息附加堆栈跟踪
attachScreenshot
boolean
false
错误发生时捕获截图(SDK ≥4.11.0)
attachViewHierarchy
boolean
false
附加JSON视图层级作为附件
debug
boolean
false
启用SDK详细日志。生产环境切勿使用
enabled
boolean
true
完全禁用SDK(例如测试场景)
ignoreErrors
string[] | RegExp[]
忽略匹配这些模式的错误
ignoreTransactions
string[] | RegExp[]
忽略匹配这些模式的事务
maxCacheItems
number
30
离线缓存的最大信封数量
defaultIntegrations
boolean
true
设置为
false
以禁用所有默认集成
integrations
array | function
添加或过滤集成

Tracing Options

链路追踪选项

OptionTypeDefaultPurpose
tracesSampleRate
number
0
Transaction sample rate (0–1). Use
1.0
in dev
tracesSampler
function
Per-transaction sampling; overrides
tracesSampleRate
tracePropagationTargets
(string | RegExp)[]
[/.*/]
Which API URLs receive distributed tracing headers
profilesSampleRate
number
0
Profiling sample rate (applied to traced transactions)
选项类型默认值用途
tracesSampleRate
number
0
事务抽样率(0–1)。开发环境使用
1.0
tracesSampler
function
按事务抽样;优先级高于
tracesSampleRate
tracePropagationTargets
(string | RegExp)[]
[/.*/]
哪些API URL会接收分布式追踪头
profilesSampleRate
number
0
性能分析抽样率(仅应用于被追踪的事务)

Native / Mobile Options

原生/移动端选项

OptionTypeDefaultPurpose
enableNative
boolean
true
Set
false
for JS-only (no native SDK)
enableNativeCrashHandling
boolean
true
Capture native hard crashes (iOS/Android)
enableNativeFramesTracking
boolean
Slow/frozen frames tracking. Disable in Expo Go
enableWatchdogTerminationTracking
boolean
true
OOM kill detection (iOS)
enableAppHangTracking
boolean
true
App hang detection (iOS, tvOS, macOS)
appHangTimeoutInterval
number
2
Seconds before classifying as app hang (iOS)
enableAutoPerformanceTracing
boolean
true
Auto performance instrumentation
enableNdkScopeSync
boolean
true
Java→NDK scope sync (Android)
attachThreads
boolean
false
Auto-attach all threads on crash (Android)
autoInitializeNativeSdk
boolean
true
Set
false
for manual native init
onReady
function
Callback after native SDKs initialize
选项类型默认值用途
enableNative
boolean
true
设置为
false
仅使用JS层(不加载原生SDK)
enableNativeCrashHandling
boolean
true
捕获原生硬崩溃(iOS/Android)
enableNativeFramesTracking
boolean
慢帧/冻结帧追踪。Expo Go中禁用
enableWatchdogTerminationTracking
boolean
true
OOM kill检测(iOS)
enableAppHangTracking
boolean
true
应用卡顿检测(iOS、tvOS、macOS)
appHangTimeoutInterval
number
2
判定为应用卡顿的秒数(iOS)
enableAutoPerformanceTracing
boolean
true
自动性能埋点
enableNdkScopeSync
boolean
true
Java→NDK上下文同步(Android)
attachThreads
boolean
false
崩溃时自动附加所有线程信息(Android)
autoInitializeNativeSdk
boolean
true
设置为
false
以手动初始化原生SDK
onReady
function
原生SDK初始化完成后的回调

Session & Release Health Options

会话与版本健康选项

OptionTypeDefaultPurpose
autoSessionTracking
boolean
true
Session tracking (crash-free users/sessions)
sessionTrackingIntervalMillis
number
30000
ms of background before session ends
选项类型默认值用途
autoSessionTracking
boolean
true
会话追踪(无崩溃用户/会话统计)
sessionTrackingIntervalMillis
number
30000
应用进入后台后会话结束的毫秒数

Replay Options

会话重放选项

OptionTypeDefaultPurpose
replaysSessionSampleRate
number
0
Fraction of all sessions recorded
replaysOnErrorSampleRate
number
0
Fraction of error sessions recorded
选项类型默认值用途
replaysSessionSampleRate
number
0
录制的会话比例
replaysOnErrorSampleRate
number
0
发生错误时录制的会话比例

Logging Options (SDK ≥7.0.0)

日志选项(SDK ≥7.0.0)

OptionTypePurpose
enableLogs
boolean
Enable
Sentry.logger.*
API
beforeSendLog
function
Filter/modify logs before sending
logsOrigin
'native' | 'js' | 'all'
Filter log source (SDK ≥7.7.0)
选项类型用途
enableLogs
boolean
启用
Sentry.logger.*
API
beforeSendLog
function
发送前过滤/修改日志
logsOrigin
'native' | 'js' | 'all'
过滤日志来源(SDK ≥7.7.0)

Hook Options

钩子选项

OptionTypePurpose
beforeSend
(event, hint) => event | null
Modify/drop JS error events. ⚠️ Does NOT apply to native crashes
beforeSendTransaction
(event) => event | null
Modify/drop transaction events
beforeBreadcrumb
(breadcrumb, hint) => breadcrumb | null
Process breadcrumbs before storage

选项类型用途
beforeSend
(event, hint) => event | null
修改/丢弃JS错误事件。⚠️ 不适用于原生崩溃
beforeSendTransaction
(event) => event | null
修改/丢弃事务事件
beforeBreadcrumb
(breadcrumb, hint) => breadcrumb | null
存储前处理面包屑

Environment Variables

环境变量

VariablePurposeNotes
SENTRY_DSN
Data Source NameFalls back from
dsn
option
SENTRY_AUTH_TOKEN
Upload source maps and dSYMsNever commit — use CI secrets
SENTRY_ORG
Organization slugUsed by wizard and build plugins
SENTRY_PROJECT
Project slugUsed by wizard and build plugins
SENTRY_RELEASE
Release identifierFalls back from
release
option
SENTRY_ENVIRONMENT
Environment nameFalls back from
environment
option
SENTRY_DISABLE_AUTO_UPLOAD
Skip source map uploadSet
true
during local builds
EXPO_PUBLIC_SENTRY_DSN
Expo public env var for DSNSafe to embed in client bundle

变量用途说明
SENTRY_DSN
数据源标识优先级低于
dsn
配置项
SENTRY_AUTH_TOKEN
上传source map和dSYM切勿提交——使用CI密钥管理
SENTRY_ORG
组织标识向导工具和构建插件使用
SENTRY_PROJECT
项目标识向导工具和构建插件使用
SENTRY_RELEASE
版本标识优先级低于
release
配置项
SENTRY_ENVIRONMENT
环境名称优先级低于
environment
配置项
SENTRY_DISABLE_AUTO_UPLOAD
跳过source map上传本地构建时设置为
true
EXPO_PUBLIC_SENTRY_DSN
Expo公开环境变量用于DSN可安全嵌入客户端包

Source Maps & Debug Symbols

Source Map与调试符号

Source maps and debug symbols are what transform minified stack traces into readable ones. When set up correctly, Sentry shows you the exact line of your source code that threw.
Source Map和调试符号用于将混淆后的堆栈跟踪转换为可读的代码位置。配置正确后,Sentry会显示抛出错误的源代码具体行号。

How Uploads Work

上传机制

PlatformWhat's uploadedWhen
iOS (JS)Source maps (
.map
files)
During Xcode build
iOS (Native)dSYM bundlesDuring Xcode archive / Xcode Cloud
Android (JS)Source maps + Hermes
.hbc.map
During Gradle build
Android (Native)Proguard mapping + NDK
.so
files
During Gradle build
平台上传内容时机
iOS(JS层)Source Map(
.map
文件)
Xcode构建时
iOS(原生)dSYM包Xcode归档 / Xcode Cloud构建时
Android(JS层)Source Map + Hermes
.hbc.map
Gradle构建时
Android(原生)ProGuard映射 + NDK
.so
文件
Gradle构建时

Expo: Automatic Upload

Expo:自动上传

The
@sentry/react-native/expo
config plugin automatically sets up upload hooks for native builds. Source maps are uploaded during
eas build
and
expo run:ios/android
(release).
bash
SENTRY_AUTH_TOKEN=sntrys_... npx expo run:ios --configuration Release
@sentry/react-native/expo
配置插件会自动为原生构建设置上传钩子。Source Map会在
eas build
expo run:ios/android
(Release模式)时自动上传。
bash
SENTRY_AUTH_TOKEN=sntrys_... npx expo run:ios --configuration Release

Manual Upload (bare RN)

手动上传(裸RN)

If you need to manually upload source maps:
bash
npx sentry-cli sourcemaps upload \
  --org YOUR_ORG \
  --project YOUR_PROJECT \
  --release "my-app@1.0.0+1" \
  ./dist

如果需要手动上传Source Map:
bash
npx sentry-cli sourcemaps upload \
  --org 你的组织标识 \
  --project 你的项目标识 \
  --release "my-app@1.0.0+1" \
  ./dist

Default Integrations (Auto-Enabled)

默认集成(自动启用)

These integrations are enabled automatically — no config needed:
IntegrationWhat it does
ReactNativeErrorHandlers
Catches unhandled JS exceptions and promise rejections
Release
Attaches release/dist to all events
Breadcrumbs
Records console logs, HTTP requests, user gestures as breadcrumbs
HttpClient
Adds HTTP request/response breadcrumbs
DeviceContext
Attaches device/OS/battery info to events
AppContext
Attaches app version, bundle ID, and memory info
CultureContext
Attaches locale and timezone
Screenshot
Captures screenshot on error (when
attachScreenshot: true
)
ViewHierarchy
Attaches view hierarchy (when
attachViewHierarchy: true
)
NativeLinkedErrors
Links JS errors to their native crash counterparts
以下集成会自动启用——无需额外配置:
集成功能
ReactNativeErrorHandlers
捕获未处理的JS异常和Promise拒绝
Release
为所有事件附加版本/构建编号
Breadcrumbs
记录控制台日志、HTTP请求、用户手势作为面包屑
HttpClient
为HTTP请求/响应添加面包屑
DeviceContext
为事件附加设备/系统/电池信息
AppContext
为事件附加应用版本、Bundle ID和内存信息
CultureContext
为事件附加区域和时区信息
Screenshot
错误发生时捕获截图(需设置
attachScreenshot: true
ViewHierarchy
附加视图层级JSON作为附件(需设置
attachViewHierarchy: true
NativeLinkedErrors
将JS错误与对应的原生崩溃关联

Opt-In Integrations

可选集成

IntegrationHow to enable
mobileReplayIntegration()
Add to
integrations
array
reactNavigationIntegration()
Add to
integrations
array
reactNativeNavigationIntegration()
Add to
integrations
array (Wix only)
feedbackIntegration()
Add to
integrations
array (user feedback widget)

集成启用方式
mobileReplayIntegration()
添加到
integrations
数组
reactNavigationIntegration()
添加到
integrations
数组
reactNativeNavigationIntegration()
添加到
integrations
数组(仅Wix版本)
feedbackIntegration()
添加到
integrations
数组(用户反馈组件)

Expo Config Plugin Reference

Expo配置插件参考

Configure the plugin in
app.json
or
app.config.js
:
json
{
  "expo": {
    "plugins": [
      [
        "@sentry/react-native/expo",
        {
          "url": "https://sentry.io/",
          "project": "my-project",
          "organization": "my-org",
          "note": "Set SENTRY_AUTH_TOKEN env var for native builds"
        }
      ]
    ]
  }
}
Or in
app.config.js
(allows env var interpolation):
javascript
export default {
  expo: {
    plugins: [
      [
        "@sentry/react-native/expo",
        {
          url: "https://sentry.io/",
          project: process.env.SENTRY_PROJECT,
          organization: process.env.SENTRY_ORG,
        },
      ],
    ],
  },
};

app.json
app.config.js
中配置插件:
json
{
  "expo": {
    "plugins": [
      [
        "@sentry/react-native/expo",
        {
          "url": "https://sentry.io/",
          "project": "my-project",
          "organization": "my-org",
          "note": "为原生构建设置SENTRY_AUTH_TOKEN环境变量"
        }
      ]
    ]
  }
}
或在
app.config.js
中配置(支持环境变量插值):
javascript
export default {
  expo: {
    plugins: [
      [
        "@sentry/react-native/expo",
        {
          url: "https://sentry.io/",
          project: process.env.SENTRY_PROJECT,
          organization: process.env.SENTRY_ORG,
        },
      ],
    ],
  },
};

Production Settings

生产环境配置

Lower sample rates and harden config before shipping to production:
typescript
Sentry.init({
  dsn: process.env.EXPO_PUBLIC_SENTRY_DSN,
  environment: __DEV__ ? "development" : "production",

  // Trace 10–20% of transactions in high-traffic production
  tracesSampleRate: __DEV__ ? 1.0 : 0.1,

  // Profile 100% of traced transactions (profiling is always a subset of tracing)
  profilesSampleRate: 1.0,

  // Replay all error sessions, sample 5% of normal sessions
  replaysOnErrorSampleRate: 1.0,
  replaysSessionSampleRate: __DEV__ ? 1.0 : 0.05,

  // Set release and dist for accurate source map lookup
  release: "my-app@" + Application.nativeApplicationVersion,
  dist: String(Application.nativeBuildVersion),

  // Disable debug logging in production
  debug: __DEV__,
});

上线前降低抽样率并加固配置:
typescript
Sentry.init({
  dsn: process.env.EXPO_PUBLIC_SENTRY_DSN,
  environment: __DEV__ ? "development" : "production",

  // 高流量生产环境追踪10–20%的事务
  tracesSampleRate: __DEV__ ? 1.0 : 0.1,

  // 对所有被追踪的事务进行分析(分析始终是追踪的子集)
  profilesSampleRate: 1.0,

  // 重放所有错误会话,抽样5%的正常会话
  replaysOnErrorSampleRate: 1.0,
  replaysSessionSampleRate: __DEV__ ? 1.0 : 0.05,

  // 设置版本号和构建编号以确保Source Map正确关联
  release: "my-app@" + Application.nativeApplicationVersion,
  dist: String(Application.nativeBuildVersion),

  // 生产环境禁用调试日志
  debug: __DEV__,
});

Verification

验证

After setup, test that Sentry is receiving events:
typescript
// Quick test — throws and Sentry.wrap(App) catches it
<Button
  title="Test Sentry Error"
  onPress={() => {
    throw new Error("My first Sentry error!");
  }}
/>

// Or capture manually
<Button
  title="Test Sentry Message"
  onPress={() => {
    Sentry.captureMessage("Sentry test message", "info");
  }}
/>
Check the Sentry dashboard:
  • Issues → your test error should appear within seconds
  • Traces → look for a "main" transaction with child spans
  • Replays → session recording visible after app interaction (native build only — not Expo Go)
  • Logs → structured log entries if
    enableLogs: true
⚠️ Expo Go limitation: Native crashes, session replay, slow/frozen frames, TTID, and TTFD only work in native builds (
eas build
or
expo run
). Expo Go runs in a JS-only mode. Set
enableNativeFramesTracking: !isRunningInExpoGo()
to avoid warnings.
If nothing appears:
  1. Set
    debug: true
    — SDK logs to Metro console
  2. Verify DSN is correct and the Sentry project exists
  3. Ensure
    Sentry.wrap(App)
    is applied to the root component
  4. For native crashes, build a release build (crashes in debug mode may not forward)

设置完成后,测试Sentry是否能接收事件:
typescript
// 快速测试——抛出错误,Sentry.wrap(App)会捕获
<Button
  title="测试Sentry错误"
  onPress={() => {
    throw new Error("我的第一个Sentry错误!");
  }}
/>

// 或手动捕获
<Button
  title="测试Sentry消息"
  onPress={() => {
    Sentry.captureMessage("Sentry测试消息", "info");
  }}
/>
检查Sentry控制台:
  • Issues → 测试错误应在几秒内出现
  • Traces → 查看名为“main”的事务及其子Span
  • Replays → 应用交互后可查看会话录制(仅原生构建支持——Expo Go不支持)
  • Logs → 若启用
    enableLogs: true
    ,可查看结构化日志条目
⚠️ Expo Go限制: 原生崩溃、会话重放、慢帧/冻结帧、TTID和TTFD仅在原生构建(
eas build
expo run
)中生效。Expo Go仅运行JS层。请设置
enableNativeFramesTracking: !isRunningInExpoGo()
以避免警告。
如果没有事件出现:
  1. 设置
    debug: true
    ——SDK会在Metro控制台输出日志
  2. 验证DSN是否正确,Sentry项目是否存在
  3. 确保
    Sentry.wrap(App)
    已应用于根组件
  4. 原生崩溃测试需要使用Release构建(Debug模式下的崩溃可能不会上报)

Phase 4: Cross-Link

第四阶段:跨链路关联

After completing React Native setup, check for a backend or web frontend missing Sentry coverage:
bash
undefined
完成React Native设置后,检查是否存在未配置Sentry的后端或Web前端:
bash
undefined

Adjacent backend directories

相邻的后端目录

ls ../backend ../server ../api 2>/dev/null cat ../go.mod 2>/dev/null | head -3 cat ../requirements.txt ../pyproject.toml 2>/dev/null | head -3 cat ../Gemfile 2>/dev/null | head -3 ls ../backend/package.json ../server/package.json 2>/dev/null
ls ../backend ../server ../api 2>/dev/null cat ../go.mod 2>/dev/null | head -3 cat ../requirements.txt ../pyproject.toml 2>/dev/null | head -3 cat ../Gemfile 2>/dev/null | head -3 ls ../backend/package.json ../server/package.json 2>/dev/null

Web frontend in same or sibling repo

同仓库或子仓库中的Web前端

ls ../web ../frontend ../dashboard 2>/dev/null cat ../web/package.json ../frontend/package.json 2>/dev/null | grep -E '"react"|"svelte"|"next"'
ls ../web ../frontend ../dashboard 2>/dev/null cat ../web/package.json ../frontend/package.json 2>/dev/null | grep -E '"react"|"svelte"|"next"'

Check for OpenTelemetry (for distributed tracing interop)

检查OpenTelemetry(用于分布式追踪互通)

grep -r "opentelemetry" ../backend/go.mod ../server/requirements.txt 2>/dev/null

If a backend or web frontend exists without Sentry, suggest the matching skill:

| Detected | Suggest skill |
|----------|--------------|
| Go backend (`go.mod`) | `sentry-go-sdk` |
| Python backend (`requirements.txt`, `pyproject.toml`) | `sentry-python-sdk` |
| Ruby backend (`Gemfile`) | `sentry-ruby-sdk` |
| Node.js backend (Express, Fastify, etc.) | `@sentry/node` — see [docs.sentry.io/platforms/javascript/guides/express/](https://docs.sentry.io/platforms/javascript/guides/express/) |
| React / Next.js web | `sentry-react-sdk` |
| Svelte / SvelteKit web | `sentry-svelte-sdk` |

**Distributed tracing setup** — if the backend skill is added, configure `tracePropagationTargets` in React Native to propagate trace context to your API:

```typescript
Sentry.init({
  tracePropagationTargets: [
    "localhost",
    /^https:\/\/api\.yourapp\.com/,
  ],
  // ...
});
This links mobile transactions to backend traces in the Sentry waterfall view.

grep -r "opentelemetry" ../backend/go.mod ../server/requirements.txt 2>/dev/null

如果存在未配置Sentry的后端或Web前端,建议使用对应的技能:

| 检测到的项目 | 推荐技能 |
|----------|--------------|
| Go后端(`go.mod`) | `sentry-go-sdk` |
| Python后端(`requirements.txt`、`pyproject.toml`) | `sentry-python-sdk` |
| Ruby后端(`Gemfile`) | `sentry-ruby-sdk` |
| Node.js后端(Express、Fastify等) | `@sentry/node` —— 参考[官方文档](https://docs.sentry.io/platforms/javascript/guides/express/) |
| React / Next.js Web | `sentry-react-sdk` |
| Svelte / SvelteKit Web | `sentry-svelte-sdk` |

**分布式追踪配置** —— 如果添加了后端技能,请在React Native中配置`tracePropagationTargets`以将追踪上下文传递给你的API:

```typescript
Sentry.init({
  tracePropagationTargets: [
    "localhost",
    /^https:\/\/api\.yourapp\.com/,
  ],
  // ...
});
这会在Sentry的瀑布视图中将移动端事务与后端追踪关联起来。

Troubleshooting

故障排查

IssueSolution
Events not appearing in SentrySet
debug: true
, check Metro/Xcode console for SDK errors; verify DSN is correct
pod install
fails
Run
cd ios && pod install --repo-update
; check CocoaPods version
iOS build fails with Sentry scriptVerify the "Bundle React Native code and images" script was replaced (not appended to)
Android build fails after adding
sentry.gradle
Ensure
apply from
line is before the
android {}
block in
build.gradle
Android Gradle 8+ compatibility issueUse
sentry-android-gradle-plugin
≥4.0.0; check
sentry.gradle
version in your SDK
Source maps not uploadingVerify
sentry.properties
has a valid
auth.token
; check build logs for
sentry-cli
output
Source maps not resolving in SentryConfirm
release
and
dist
in
Sentry.init()
match the uploaded bundle metadata
Hermes source maps not workingHermes emits
.hbc.map
— the Gradle plugin handles this automatically; verify
sentry.gradle
is applied
Session replay not recordingMust use a native build (not Expo Go); confirm
mobileReplayIntegration()
is in
integrations
Replay shows blank/black screensCheck that
maskAllText
/
maskAllImages
settings match your privacy requirements
Slow/frozen frames not trackedSet
enableNativeFramesTracking: true
and confirm you're on a native build (not Expo Go)
TTID / TTFD not appearingRequires
enableTimeToInitialDisplay: true
in
reactNavigationIntegration()
on a native build
App crashes on startup after adding SentryLikely a native initialization error — check Xcode/Logcat logs; try
enableNative: false
to isolate
Expo SDK 49 or olderUse
sentry-expo
(legacy package);
@sentry/react-native
requires Expo SDK 50+
isRunningInExpoGo
import error
Import from
expo
package:
import { isRunningInExpoGo } from "expo"
Node not found during Xcode buildAdd
export NODE_BINARY=$(which node)
to the Xcode build phase, or symlink:
ln -s $(which node) /usr/local/bin/node
Expo Go warning about native featuresUse
isRunningInExpoGo()
guard:
enableNativeFramesTracking: !isRunningInExpoGo()
beforeSend
not firing for native crashes
Expected —
beforeSend
only intercepts JS-layer errors; native crashes bypass it
Android 15+ (16KB page size) crashUpgrade to
@sentry/react-native
≥6.3.0
Too many transactions in dashboardLower
tracesSampleRate
to
0.1
or use
tracesSampler
to drop health checks
SENTRY_AUTH_TOKEN
exposed in app bundle
SENTRY_AUTH_TOKEN
is for build-time upload only — never pass it to
Sentry.init()
EAS Build: Sentry auth token missingSet
SENTRY_AUTH_TOKEN
as an EAS secret:
eas secret:create --name SENTRY_AUTH_TOKEN
问题解决方案
事件未出现在Sentry中设置
debug: true
,检查Metro/Xcode控制台的SDK错误;验证DSN是否正确
pod install
失败
运行
cd ios && pod install --repo-update
;检查CocoaPods版本
iOS构建时Sentry脚本报错确认“Bundle React Native code and images”脚本已被替换(而非追加)
添加
sentry.gradle
后Android构建失败
确保
apply from
行位于
build.gradle
android {}
块之前
Android Gradle 8+兼容性问题使用
sentry-android-gradle-plugin
≥4.0.0;检查SDK中
sentry.gradle
的版本
Source Map未上传验证
sentry.properties
中的
auth.token
是否有效;检查构建日志中的
sentry-cli
输出
Source Map在Sentry中无法解析确认
Sentry.init()
中的
release
dist
与上传包的元数据匹配
Hermes Source Map不生效Hermes会生成
.hbc.map
——Gradle插件会自动处理;确认
sentry.gradle
已应用
会话重放未录制必须使用原生构建(非Expo Go);确认
mobileReplayIntegration()
已添加到
integrations
重放显示空白/黑屏检查
maskAllText
/
maskAllImages
设置是否符合隐私要求
慢帧/冻结帧未追踪设置
enableNativeFramesTracking: true
并确认使用原生构建(非Expo Go)
TTID / TTFD未显示需要在
reactNavigationIntegration()
中设置
enableTimeToInitialDisplay: true
并使用原生构建
添加Sentry后应用启动崩溃可能是原生初始化错误——检查Xcode/Logcat日志;尝试设置
enableNative: false
以隔离问题
Expo SDK 49或更低版本使用
sentry-expo
(已废弃包);
@sentry/react-native
需要Expo SDK 50+
isRunningInExpoGo
导入错误
expo
包导入:
import { isRunningInExpoGo } from "expo"
Xcode构建时提示Node未找到在Xcode构建阶段添加
export NODE_BINARY=$(which node)
,或创建软链接:
ln -s $(which node) /usr/local/bin/node
Expo Go中出现原生功能警告使用
isRunningInExpoGo()
判断:
enableNativeFramesTracking: !isRunningInExpoGo()
beforeSend
对原生崩溃不生效
预期行为——
beforeSend
仅拦截JS层错误;原生崩溃会绕过该钩子
Android 15+(16KB页面大小)崩溃升级到
@sentry/react-native
≥6.3.0
控制台中事务数量过多
tracesSampleRate
降低至
0.1
或使用
tracesSampler
丢弃健康检查类事务
SENTRY_AUTH_TOKEN
在应用包中暴露
SENTRY_AUTH_TOKEN
仅用于构建时上传——切勿传递给
Sentry.init()
EAS Build提示Sentry授权令牌缺失
SENTRY_AUTH_TOKEN
设置为EAS密钥:
eas secret:create --name SENTRY_AUTH_TOKEN