sentry-cloudflare-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAll Skills > SDK Setup > Cloudflare SDK
所有技能 > SDK 设置 > Cloudflare SDK
Sentry Cloudflare SDK
Sentry Cloudflare SDK
Opinionated wizard that scans your Cloudflare project and guides you through complete Sentry setup for Workers, Pages, Durable Objects, Queues, Workflows, and Hono.
这是一个预设规则的向导工具,会扫描你的Cloudflare项目,并引导你完成Workers、Pages、Durable Objects、Queues、Workflows和Hono的完整Sentry配置。
Invoke This Skill When
何时调用本技能
- User asks to "add Sentry to Cloudflare Workers" or "set up Sentry" in a Cloudflare project
- User wants to install or configure
@sentry/cloudflare - User wants error monitoring, tracing, logging, crons, or AI monitoring for Cloudflare Workers or Pages
- User asks about ,
withSentry,sentryPagesPlugin, orinstrumentDurableObjectWithSentryinstrumentD1WithSentry - User wants to monitor Durable Objects, Queues, Workflows, Scheduled handlers, or Email handlers on Cloudflare
Note: SDK versions and APIs below reflect current Sentry docs at time of writing (v10.43.0). Always verify against docs.sentry.io/platforms/javascript/guides/cloudflare/ before implementing.@sentry/cloudflare
- 用户要求“为Cloudflare Workers添加Sentry”或在Cloudflare项目中“设置Sentry”
- 用户想要安装或配置
@sentry/cloudflare - 用户想要为Cloudflare Workers或Pages配置错误监控、链路追踪、日志记录、定时任务监控或AI监控
- 用户询问、
withSentry、sentryPagesPlugin或instrumentDurableObjectWithSentry相关内容instrumentD1WithSentry - 用户想要监控Cloudflare上的Durable Objects、Queues、Workflows、定时处理器或邮件处理器
注意: 以下SDK版本和API基于编写时的最新Sentry文档(v10.43.0)。 实施前请务必对照Sentry官方文档进行验证。@sentry/cloudflare
Phase 1: Detect
阶段1:项目检测
Run these commands to understand the project before making any recommendations:
bash
undefined在给出任何建议前,先运行以下命令了解项目情况:
bash
undefinedDetect Cloudflare project
检测Cloudflare项目
ls wrangler.toml wrangler.jsonc wrangler.json 2>/dev/null
ls wrangler.toml wrangler.jsonc wrangler.json 2>/dev/null
Detect existing Sentry
检测已安装的Sentry
cat package.json 2>/dev/null | grep -E '"@sentry/'
cat package.json 2>/dev/null | grep -E '"@sentry/'
Detect project type (Workers vs Pages)
检测项目类型(Workers 或 Pages)
ls functions/ functions/_middleware.js functions/_middleware.ts 2>/dev/null && echo "Pages detected"
cat wrangler.toml 2>/dev/null | grep -E 'main|pages_build_output_dir'
ls functions/ functions/_middleware.js functions/_middleware.ts 2>/dev/null && echo "Pages detected"
cat wrangler.toml 2>/dev/null | grep -E 'main|pages_build_output_dir'
Detect framework
检测框架
cat package.json 2>/dev/null | grep -E '"hono"|"remix"|"astro"|"svelte"'
cat package.json 2>/dev/null | grep -E '"hono"|"remix"|"astro"|"svelte"'
Detect Durable Objects
检测Durable Objects
cat wrangler.toml 2>/dev/null | grep -i 'durable_objects'
cat wrangler.toml 2>/dev/null | grep -i 'durable_objects'
Detect D1 databases
检测D1数据库
cat wrangler.toml 2>/dev/null | grep -i 'd1_databases'
cat wrangler.toml 2>/dev/null | grep -i 'd1_databases'
Detect Queues
检测Queues
cat wrangler.toml 2>/dev/null | grep -i 'queues'
cat wrangler.toml 2>/dev/null | grep -i 'queues'
Detect Workflows
检测Workflows
cat wrangler.toml 2>/dev/null | grep -i 'workflows'
cat wrangler.toml 2>/dev/null | grep -i 'workflows'
Detect Scheduled handlers (cron triggers)
检测定时处理器(Cron触发器)
cat wrangler.toml 2>/dev/null | grep -i 'crons|triggers'
cat wrangler.toml 2>/dev/null | grep -i 'crons\|triggers'
Detect compatibility flags
检测兼容性标志
cat wrangler.toml 2>/dev/null | grep -i 'compatibility_flags'
cat wrangler.jsonc 2>/dev/null | grep -i 'compatibility_flags'
cat wrangler.toml 2>/dev/null | grep -i 'compatibility_flags'
cat wrangler.jsonc 2>/dev/null | grep -i 'compatibility_flags'
Detect AI/LLM libraries
检测AI/LLM库
cat package.json 2>/dev/null | grep -E '"openai"|"@anthropic-ai"|"ai"|"@google/generative-ai"|"@langchain"'
cat package.json 2>/dev/null | grep -E '"openai"|"@anthropic-ai"|"ai"|"@google/generative-ai"|"@langchain"'
Detect logging libraries
检测日志库
cat package.json 2>/dev/null | grep -E '"pino"|"winston"'
cat package.json 2>/dev/null | grep -E '"pino"|"winston"'
Check for companion frontend
检查是否存在配套前端
ls frontend/ web/ client/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'
**What to determine:**
| Question | Impact |
|----------|--------|
| Workers or Pages? | Determines wrapper: `withSentry` vs `sentryPagesPlugin` |
| Hono framework? | Automatic Hono error handler integration via `honoIntegration` |
| `@sentry/cloudflare` already installed? | Skip install, go to feature config |
| Durable Objects configured? | Recommend `instrumentDurableObjectWithSentry` |
| D1 databases bound? | Recommend `instrumentD1WithSentry` |
| Queues configured? | `withSentry` auto-instruments queue handlers |
| Workflows configured? | Recommend `instrumentWorkflowWithSentry` |
| Cron triggers configured? | `withSentry` auto-instruments scheduled handlers; recommend Crons monitoring |
| `nodejs_als` or `nodejs_compat` flag set? | **Required** — SDK needs `AsyncLocalStorage` |
| AI/LLM libraries? | Recommend AI Monitoring integrations |
| Companion frontend? | Trigger Phase 4 cross-link |
---ls frontend/ web/ client/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'
**需要确定的信息:**
| 问题 | 影响 |
|----------|--------|
| 是Workers还是Pages? | 决定使用的包装器:`withSentry` 还是 `sentryPagesPlugin` |
| 是否使用Hono框架? | 通过`honoIntegration`自动集成Hono错误处理器 |
| 是否已安装`@sentry/cloudflare`? | 跳过安装步骤,直接进入功能配置 |
| 是否已配置Durable Objects? | 推荐使用`instrumentDurableObjectWithSentry` |
| 是否已绑定D1数据库? | 推荐使用`instrumentD1WithSentry` |
| 是否已配置Queues? | `withSentry`会自动为队列处理器添加埋点 |
| 是否已配置Workflows? | 推荐使用`instrumentWorkflowWithSentry` |
| 是否已配置Cron触发器? | `withSentry`会自动为定时处理器添加埋点;推荐配置定时任务监控 |
| 是否设置了`nodejs_als`或`nodejs_compat`标志? | **必填项** — SDK需要`AsyncLocalStorage`支持 |
| 是否使用AI/LLM库? | 推荐配置AI监控集成 |
| 是否存在配套前端? | 触发阶段4的跨服务关联配置 |
---Phase 2: Recommend
阶段2:配置建议
Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:
Recommended (core coverage):
- ✅ Error Monitoring — always; captures unhandled exceptions in fetch, scheduled, queue, email, and Durable Object handlers
- ✅ Tracing — automatic HTTP request spans, outbound fetch tracing, D1 query spans
Optional (enhanced observability):
- ⚡ Logging — structured logs via ; recommend when log search is needed
Sentry.logger.* - ⚡ Crons — detect missed/failed scheduled jobs; recommend when cron triggers are configured
- ⚡ D1 Instrumentation — automatic query spans and breadcrumbs; recommend when D1 is bound
- ⚡ Durable Objects — automatic error capture and spans for DO methods; recommend when DOs are configured
- ⚡ Workflows — automatic span creation for workflow steps; recommend when Workflows are configured
- ⚡ AI Monitoring — Vercel AI SDK, OpenAI, Anthropic, LangChain; recommend when AI libraries detected
Recommendation logic:
| Feature | Recommend when... |
|---|---|
| Error Monitoring | Always — non-negotiable baseline |
| Tracing | Always — HTTP request tracing and outbound fetch are high-value |
| Logging | App needs structured log search or log-to-trace correlation |
| Crons | Cron triggers configured in |
| D1 Instrumentation | D1 database bindings present |
| Durable Objects | Durable Object bindings configured |
| Workflows | Workflow bindings configured |
| AI Monitoring | App uses Vercel AI SDK, OpenAI, Anthropic, or LangChain |
| Metrics | App needs custom counters, gauges, or distributions |
Propose: "I recommend setting up Error Monitoring + Tracing. Want me to also add D1 instrumentation and Crons monitoring?"
根据检测结果给出具体的配置建议,不要提出开放式问题,直接给出方案:
推荐(核心覆盖):
- ✅ 错误监控 — 必选;捕获fetch、定时、队列、邮件和Durable Object处理器中的未处理异常
- ✅ 链路追踪 — 自动生成HTTP请求链路、出站fetch追踪、D1查询链路
可选(增强可观测性):
- ⚡ 日志记录 — 通过生成结构化日志;当需要日志搜索时推荐配置
Sentry.logger.* - ⚡ 定时任务监控 — 检测定时任务的遗漏/失败情况;当配置了Cron触发器时推荐配置
- ⚡ D1埋点 — 自动生成查询链路和运行轨迹;当绑定了D1数据库时推荐配置
- ⚡ Durable Objects监控 — 自动捕获DO方法的错误并生成链路;当配置了DO时推荐配置
- ⚡ Workflows监控 — 自动为工作流步骤生成链路;当配置了Workflows时推荐配置
- ⚡ AI监控 — 支持Vercel AI SDK、OpenAI、Anthropic、LangChain;当检测到AI库时推荐配置
建议逻辑:
| 功能 | 推荐场景 |
|---|---|
| 错误监控 | 始终必选 — 不可缺少的基础配置 |
| 链路追踪 | 始终必选 — HTTP请求追踪和出站fetch追踪价值极高 |
| 日志记录 | 应用需要结构化日志搜索或日志与链路关联时 |
| 定时任务监控 | |
| D1埋点 | 存在D1数据库绑定时 |
| Durable Objects监控 | 配置了Durable Objects绑定时 |
| Workflows监控 | 配置了Workflows绑定时 |
| AI监控 | 应用使用Vercel AI SDK、OpenAI、Anthropic或LangChain时 |
| 指标监控 | 应用需要自定义计数器、仪表盘或分布统计时 |
建议话术示例:"我建议配置错误监控+链路追踪。是否需要同时添加D1埋点和定时任务监控?"
Phase 3: Guide
阶段3:配置引导
Option 1: Source Maps Wizard
选项1:Source Maps向导
You need to run this yourself — the wizard opens a browser for login and requires interactive input that the agent can't handle. Copy-paste into your terminal:npx @sentry/wizard@latest -i sourcemapsThis sets up source map uploading so your production stack traces show readable code. It does not set up the SDK initialization — you still need to follow Option 2 below for the actual SDK setup.Once it finishes, continue with Option 2 for SDK setup.
Note: Unlike framework SDKs (Next.js, SvelteKit), there is no Cloudflare-specific wizard integration. Thewizard only handles source map upload configuration.sourcemaps
你需要自行运行此命令 — 该向导会打开浏览器进行登录,需要交互式操作,无法由代理完成。请复制以下命令到终端运行:npx @sentry/wizard@latest -i sourcemaps此命令会配置Source Map上传,让生产环境的堆栈跟踪显示可读代码。但它不会完成SDK初始化 — 你仍需要按照下方选项2完成SDK的实际设置。完成后,请继续执行选项2的SDK设置步骤。
注意: 与框架SDK(如Next.js、SvelteKit)不同,目前没有针对Cloudflare的专属向导集成。向导仅处理Source Map上传配置。sourcemaps
Option 2: Manual Setup
选项2:手动设置
Prerequisites: Compatibility Flags
前置条件:兼容性标志
The SDK requires . Add one of these flags to your Wrangler config:
AsyncLocalStoragewrangler.toml:
toml
compatibility_flags = ["nodejs_als"]SDK需要支持。请在Wrangler配置中添加以下任一标志:
AsyncLocalStoragewrangler.toml:
toml
compatibility_flags = ["nodejs_als"]or: compatibility_flags = ["nodejs_compat"]
或:compatibility_flags = ["nodejs_compat"]
**wrangler.jsonc:**
```jsonc
{
"compatibility_flags": ["nodejs_als"]
}is lighter — it only enablesnodejs_als. UseAsyncLocalStorageif your code also needs other Node.js APIs.nodejs_compat
**wrangler.jsonc:**
```jsonc
{
"compatibility_flags": ["nodejs_als"]
}更轻量 — 仅启用nodejs_als。如果你的代码还需要其他Node.js API,请使用AsyncLocalStorage。nodejs_compat
Install
安装SDK
bash
npm install @sentry/cloudflarebash
npm install @sentry/cloudflareWorkers Setup
Workers设置
Wrap your handler with . This automatically instruments , , , , and handlers:
withSentryfetchscheduledqueueemailtailtypescript
import * as Sentry from "@sentry/cloudflare";
export default Sentry.withSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
sendDefaultPii: true,
tracesSampleRate: 1.0,
enableLogs: true,
}),
{
async fetch(request, env, ctx) {
return new Response("Hello World!");
},
} satisfies ExportedHandler<Env>,
);Key points:
- The first argument is a callback that receives — use this to read secrets like
envSENTRY_DSN - The SDK reads DSN, environment, release, debug, tunnel, and traces sample rate from automatically (see Environment Variables)
env - wraps all exported handlers — you do not need separate wrappers for
withSentry,scheduled, etc.queue
使用包装你的处理器。这会自动为、、、和处理器添加埋点:
withSentryfetchscheduledqueueemailtailtypescript
import * as Sentry from "@sentry/cloudflare";
export default Sentry.withSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
sendDefaultPii: true,
tracesSampleRate: 1.0,
enableLogs: true,
}),
{
async fetch(request, env, ctx) {
return new Response("Hello World!");
},
} satisfies ExportedHandler<Env>,
);关键点:
- 第一个参数是接收的回调函数 — 用于读取
env等密钥SENTRY_DSN - SDK会自动从中读取DSN、环境、版本、调试模式、隧道和链路采样率(详见环境变量)
env - 会包装所有导出的处理器 — 你无需为
withSentry、scheduled等单独添加包装器queue
Pages Setup
Pages设置
Use as middleware:
sentryPagesPlugintypescript
// functions/_middleware.ts
import * as Sentry from "@sentry/cloudflare";
export const onRequest = Sentry.sentryPagesPlugin((context) => ({
dsn: context.env.SENTRY_DSN,
sendDefaultPii: true,
tracesSampleRate: 1.0,
enableLogs: true,
}));Chaining multiple middlewares:
typescript
import * as Sentry from "@sentry/cloudflare";
export const onRequest = [
// Sentry must be first
Sentry.sentryPagesPlugin((context) => ({
dsn: context.env.SENTRY_DSN,
tracesSampleRate: 1.0,
})),
// Add more middlewares here
];Using directly (for frameworks like SvelteKit on Cloudflare Pages):
wrapRequestHandlertypescript
import * as Sentry from "@sentry/cloudflare";
export const handle = ({ event, resolve }) => {
return Sentry.wrapRequestHandler(
{
options: {
dsn: event.platform.env.SENTRY_DSN,
tracesSampleRate: 1.0,
},
request: event.request,
context: event.platform.ctx,
},
() => resolve(event),
);
};将作为中间件使用:
sentryPagesPlugintypescript
// functions/_middleware.ts
import * as Sentry from "@sentry/cloudflare";
export const onRequest = Sentry.sentryPagesPlugin((context) => ({
dsn: context.env.SENTRY_DSN,
sendDefaultPii: true,
tracesSampleRate: 1.0,
enableLogs: true,
}));链式调用多个中间件:
typescript
import * as Sentry from "@sentry/cloudflare";
export const onRequest = [
// Sentry必须放在第一位
Sentry.sentryPagesPlugin((context) => ({
dsn: context.env.SENTRY_DSN,
tracesSampleRate: 1.0,
})),
// 在此添加其他中间件
];直接使用(适用于Cloudflare Pages上的SvelteKit等框架):
wrapRequestHandlertypescript
import * as Sentry from "@sentry/cloudflare";
export const handle = ({ event, resolve }) => {
return Sentry.wrapRequestHandler(
{
options: {
dsn: event.platform.env.SENTRY_DSN,
tracesSampleRate: 1.0,
},
request: event.request,
context: event.platform.ctx,
},
() => resolve(event),
);
};Hono on Cloudflare Workers
Cloudflare Workers上的Hono框架设置
Hono apps are objects with a method — wrap them with directly:
fetchwithSentrytypescript
import { Hono } from "hono";
import * as Sentry from "@sentry/cloudflare";
const app = new Hono();
app.get("/", (ctx) => ctx.json({ message: "Hello" }));
app.get("/error", () => {
throw new Error("Test error");
});
app.onError((err, ctx) => {
return ctx.json({ error: err.message }, 500);
});
export default Sentry.withSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
tracesSampleRate: 1.0,
}),
app,
);The (enabled by default) automatically captures errors from Hono's handler and sets the correct transaction name with the route path.
honoIntegrationonErrorHono应用是带有方法的对象 — 直接使用包装即可:
fetchwithSentrytypescript
import { Hono } from "hono";
import * as Sentry from "@sentry/cloudflare";
const app = new Hono();
app.get("/", (ctx) => ctx.json({ message: "Hello" }));
app.get("/error", () => {
throw new Error("Test error");
});
app.onError((err, ctx) => {
return ctx.json({ error: err.message }, 500);
});
export default Sentry.withSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
tracesSampleRate: 1.0,
}),
app,
);默认启用的会自动捕获Hono的处理器中的错误,并通过路由路径设置正确的事务名称。
honoIntegrationonErrorSet Up the SENTRY_DSN Secret
设置SENTRY_DSN密钥
Store your DSN as a Cloudflare secret — do not hardcode it:
bash
undefined将你的DSN存储为Cloudflare密钥 — 不要硬编码:
bash
undefinedLocal development: add to .dev.vars
本地开发:添加到.dev.vars
echo 'SENTRY_DSN="https://examplePublicKey@o0.ingest.sentry.io/0"' >> .dev.vars
echo 'SENTRY_DSN="https://examplePublicKey@o0.ingest.sentry.io/0"' >> .dev.vars
Production: set as a secret
生产环境:设置为密钥
npx wrangler secret put SENTRY_DSN
Add the binding to your `Env` type:
```typescript
interface Env {
SENTRY_DSN: string;
// ... other bindings
}npx wrangler secret put SENTRY_DSN
将绑定添加到你的`Env`类型定义中:
```typescript
interface Env {
SENTRY_DSN: string;
// ... 其他绑定
}Source Maps Setup
Source Maps设置
Source maps make production stack traces readable. Without them, you see minified/bundled code.
Step 1: Generate a Sentry auth token
Step 2: Install the Sentry Vite plugin (most Cloudflare projects use Vite via Wrangler):
bash
npm install @sentry/vite-plugin --save-devStep 3: Configure (if your project has one):
vite.config.tstypescript
import { defineConfig } from "vite";
import { sentryVitePlugin } from "@sentry/vite-plugin";
export default defineConfig({
build: {
sourcemap: true,
},
plugins: [
sentryVitePlugin({
org: "___ORG_SLUG___",
project: "___PROJECT_SLUG___",
authToken: process.env.SENTRY_AUTH_TOKEN,
}),
],
});Step 4: Set environment variables in CI
bash
SENTRY_AUTH_TOKEN=sntrys_eyJ...
SENTRY_ORG=my-org
SENTRY_PROJECT=my-projectStep 5: Add to
.gitignore.dev.vars
.env.sentry-build-pluginSource Maps可以让生产环境的堆栈跟踪显示可读代码。如果没有它,你只会看到压缩/打包后的代码。
步骤1:生成Sentry授权令牌
步骤2:安装Sentry Vite插件(大多数Cloudflare项目通过Wrangler使用Vite):
bash
npm install @sentry/vite-plugin --save-dev步骤3:配置(如果你的项目有该文件):
vite.config.tstypescript
import { defineConfig } from "vite";
import { sentryVitePlugin } from "@sentry/vite-plugin";
export default defineConfig({
build: {
sourcemap: true,
},
plugins: [
sentryVitePlugin({
org: "___ORG_SLUG___",
project: "___PROJECT_SLUG___",
authToken: process.env.SENTRY_AUTH_TOKEN,
}),
],
});步骤4:在CI中设置环境变量
bash
SENTRY_AUTH_TOKEN=sntrys_eyJ...
SENTRY_ORG=my-org
SENTRY_PROJECT=my-project步骤5:添加到
.gitignore.dev.vars
.env.sentry-build-pluginAutomatic Release Detection
自动版本检测
The SDK can automatically detect the release version via Cloudflare's version metadata binding:
wrangler.toml:
toml
[version_metadata]
binding = "CF_VERSION_METADATA"Release priority (highest to lowest):
- option passed to
releaseSentry.init() - environment variable
SENTRY_RELEASE - binding
CF_VERSION_METADATA.id
SDK可以通过Cloudflare的版本元数据绑定自动检测版本号:
wrangler.toml:
toml
[version_metadata]
binding = "CF_VERSION_METADATA"版本优先级(从高到低):
- 传递给的
Sentry.init()选项release - 环境变量
SENTRY_RELEASE - 绑定
CF_VERSION_METADATA.id
For Each Agreed Feature
针对每个确认的功能
Load the corresponding reference file and follow its steps:
| Feature | Reference file | Load when... |
|---|---|---|
| Error Monitoring | | Always (baseline) — unhandled exceptions, manual capture, scopes, enrichment |
| Tracing | | HTTP request tracing, outbound fetch spans, D1 query spans, distributed tracing |
| Logging | | Structured logs via |
| Crons | | Scheduled handler monitoring, |
| Durable Objects | | Instrument Durable Object classes for error capture and spans |
For each feature: read the reference file, follow its steps exactly, and verify before moving on.
加载对应的参考文件并按照步骤操作:
| 功能 | 参考文件 | 加载时机 |
|---|---|---|
| 错误监控 | | 始终加载(基础配置)— 未处理异常、手动捕获、作用域、事件增强 |
| 链路追踪 | | HTTP请求追踪、出站fetch链路、D1查询链路、分布式追踪 |
| 日志记录 | | 通过 |
| 定时任务监控 | | 定时处理器监控、 |
| Durable Objects监控 | | 为Durable Object类添加埋点以捕获错误和生成链路 |
针对每个功能:读取参考文件,严格按照步骤操作,并在进入下一步前进行验证。
Verification
验证配置
After setup, verify Sentry is working:
typescript
// Add temporarily to your fetch handler, then remove
export default Sentry.withSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
tracesSampleRate: 1.0,
}),
{
async fetch(request, env, ctx) {
throw new Error("Sentry test error — delete me");
},
} satisfies ExportedHandler<Env>,
);Deploy and trigger the route, then check your Sentry Issues dashboard — the error should appear within ~30 seconds.
Verification checklist:
| Check | How |
|---|---|
| Errors captured | Throw in a fetch handler, verify in Sentry |
| Tracing working | Check Performance tab for HTTP spans |
| Source maps working | Check stack trace shows readable file/line names |
| D1 spans (if configured) | Run a D1 query, check for |
| Scheduled monitoring (if configured) | Trigger a cron, check Crons dashboard |
设置完成后,验证Sentry是否正常工作:
typescript
// 临时添加到你的fetch处理器中,验证完成后删除
export default Sentry.withSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
tracesSampleRate: 1.0,
}),
{
async fetch(request, env, ctx) {
throw new Error("Sentry test error — delete me");
},
} satisfies ExportedHandler<Env>,
);部署并触发该路由,然后查看你的Sentry问题面板 — 错误应该会在约30秒内显示。
验证清单:
| 检查项 | 验证方式 |
|---|---|
| 错误捕获正常 | 在fetch处理器中抛出错误,在Sentry中验证 |
| 链路追踪正常 | 在性能面板中查看HTTP链路 |
| Source Maps正常 | 检查堆栈跟踪显示可读的文件/行号 |
| D1链路正常(若配置) | 运行D1查询,查看是否存在 |
| 定时任务监控正常(若配置) | 触发定时任务,查看定时任务面板 |
Config Reference
配置参考
Sentry.init()
Options
Sentry.init()Sentry.init()
选项
Sentry.init()| Option | Type | Default | Notes |
|---|---|---|---|
| | — | Required. Read from |
| | — | 0–1; 1.0 in dev, lower in prod recommended |
| | — | Dynamic sampling function; mutually exclusive with |
| | | Include request headers and cookies in events |
| | | Enable Sentry Logs product |
| | auto | Read from |
| | auto | Detected from |
| | | Read from |
| | — | Read from |
| | — | Filter/modify error events before sending |
| | — | Filter/modify transaction events before sending |
| | — | Filter/modify log entries before sending |
| | all URLs | Control which outbound requests get trace headers |
| | | Opt-out of OpenTelemetry compatibility tracer |
| | | Durable Object: instrument prototype methods for RPC spans |
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | — | 必填项。若未设置,会自动从 |
| | — | 0–1;开发环境推荐设为1.0,生产环境建议调低 |
| | — | 动态采样函数;与 |
| | | 在事件中包含请求头和Cookie |
| | | 启用Sentry日志产品 |
| | 自动检测 | 若未设置,会自动从 |
| | 自动检测 | 从 |
| | | 若未设置,会自动从 |
| | — | 若未设置,会自动从 |
| | — | 在发送前过滤/修改错误事件 |
| | — | 在发送前过滤/修改事务事件 |
| | — | 在发送前过滤/修改日志条目 |
| `(string\ | RegExp)[]` | 所有URL |
| | | 选择退出OpenTelemetry兼容追踪器 |
| `boolean \ | string[]` | |
Environment Variables (Read from env
)
env环境变量(从env
读取)
envThe SDK reads these from the Cloudflare object automatically:
env| Variable | Purpose |
|---|---|
| DSN for Sentry init |
| Release version string |
| Environment name ( |
| Traces sample rate (parsed as float) |
| Enable debug mode ( |
| Tunnel URL for event proxying |
| Cloudflare version metadata binding (auto-detected release) |
SDK会自动从Cloudflare的对象中读取以下变量:
env| 变量 | 用途 |
|---|---|
| Sentry初始化的DSN |
| 版本号字符串 |
| 环境名称(如 |
| 链路采样率(解析为浮点数) |
| 启用调试模式(值为 |
| 事件代理的隧道URL |
| Cloudflare版本元数据绑定(自动检测版本) |
Default Integrations
默认集成
These are registered automatically by :
getDefaultIntegrations()| Integration | Purpose |
|---|---|
| Prevent duplicate events (disabled for Workflows) |
| Filter events by type, message, URL |
| Preserve original function names |
| Follow |
| Trace outbound |
| Auto-capture Hono |
| Attach request data to events |
| Capture |
这些集成会由自动注册:
getDefaultIntegrations()| 集成 | 用途 |
|---|---|
| 防止重复事件(Workflows中禁用) |
| 按类型、消息、URL过滤事件 |
| 保留原始函数名称 |
| 追踪错误中的 |
| 追踪出站 |
| 自动捕获Hono |
| 将请求数据附加到事件中 |
| 将 |
Phase 4: Cross-Link
阶段4:跨服务关联
After completing Cloudflare setup, check for companion services:
bash
undefined完成Cloudflare设置后,检查是否存在配套服务:
bash
undefinedCheck for companion frontend
检查是否存在配套前端
ls frontend/ web/ client/ ui/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"|"astro"'
ls frontend/ web/ client/ ui/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"|"astro"'
Check for companion backend in adjacent directories
检查相邻目录中是否存在配套后端
ls ../backend ../server ../api 2>/dev/null
cat ../go.mod ../requirements.txt ../Gemfile 2>/dev/null | head -3
If a frontend is found, suggest the matching SDK skill:
| Frontend detected | Suggest skill |
|------------------|--------------|
| React | `sentry-react-sdk` |
| Next.js | `sentry-nextjs-sdk` |
| Svelte/SvelteKit | `sentry-svelte-sdk` |
| Vue/Nuxt | See [docs.sentry.io/platforms/javascript/guides/vue/](https://docs.sentry.io/platforms/javascript/guides/vue/) |
If a backend is found in a different directory:
| Backend detected | Suggest skill |
|-----------------|--------------|
| 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-sdk` |
Connecting frontend and backend with linked Sentry projects enables **distributed tracing** — stack traces that span your browser, Cloudflare Worker, and backend API in a single trace view.
---ls ../backend ../server ../api 2>/dev/null
cat ../go.mod ../requirements.txt ../Gemfile 2>/dev/null | head -3
如果检测到前端,建议使用对应的SDK技能:
| 检测到的前端 | 推荐技能 |
|------------------|--------------|
| React | `sentry-react-sdk` |
| Next.js | `sentry-nextjs-sdk` |
| Svelte/SvelteKit | `sentry-svelte-sdk` |
| Vue/Nuxt | 查看[Sentry官方文档](https://docs.sentry.io/platforms/javascript/guides/vue/) |
如果在其他目录中检测到后端:
| 检测到的后端 | 推荐技能 |
|-----------------|--------------|
| 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-sdk` |
通过关联前端和后端的Sentry项目,可以实现**分布式追踪** — 在单个追踪视图中查看跨越浏览器、Cloudflare Worker和后端API的完整堆栈跟踪。
---Troubleshooting
故障排除
| Issue | Cause | Solution |
|---|---|---|
| Events not appearing | DSN not set or | Set |
| Missing compatibility flag | Add |
| Stack traces show minified code | Source maps not uploaded | Configure |
| Events lost on short-lived requests | SDK not flushing before worker terminates | Ensure |
| Hono errors not captured | Hono app not wrapped with | Pass the Hono app as the second argument to |
| Durable Object errors missing | DO class not instrumented | Wrap class with |
| D1 queries not creating spans | D1 binding not instrumented | Wrap binding with |
| Scheduled handler not monitored | | Ensure |
| Release not auto-detected | | Add |
| Duplicate events in Workflows | Dedupe integration filtering step failures | SDK automatically disables dedupe for Workflows; verify you use |
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 事件未显示 | DSN未设置或 | 临时在初始化选项中设置 |
| 缺少兼容性标志 | 在 |
| 堆栈跟踪显示压缩代码 | Source Maps未上传 | 配置 |
| 短生命周期请求中事件丢失 | SDK未在Worker终止前刷新数据 | 确保使用 |
| Hono错误未被捕获 | Hono应用未使用 | 将Hono应用作为第二个参数传递给 |
| Durable Object错误缺失 | DO类未添加埋点 | 使用 |
| D1查询未生成链路 | D1绑定未添加埋点 | 使用 |
| 定时处理器未被监控 | | 确保 |
| 版本未自动检测 | 未配置 | 在 |
| Workflows中出现重复事件 | 去重集成过滤步骤失败 | SDK会自动为Workflows禁用去重;验证你使用了 |
| ", |