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 Triggers)
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` vs `sentryPagesPlugin` |
| 是否使用Hono框架? | 可通过`honoIntegration`自动集成Hono错误处理器 |
| 是否已安装`@sentry/cloudflare`? | 跳过安装步骤,直接进入功能配置 |
| 是否配置了Durable Objects? | 建议使用`instrumentDurableObjectWithSentry` |
| 是否绑定了D1数据库? | 建议使用`instrumentD1WithSentry` |
| 是否配置了Queues? | `withSentry`会自动为队列处理器添加监控 |
| 是否配置了Workflows? | 建议使用`instrumentWorkflowWithSentry` |
| 是否配置了定时触发器? | `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.* - ⚡ 定时任务监控 — 检测遗漏/失败的定时任务;当配置了定时触发器时推荐使用
- ⚡ D1数据库监控 — 自动捕获查询链路和运行轨迹;当绑定了D1数据库时推荐使用
- ⚡ Durable Objects监控 — 自动捕获Durable Object方法的错误和链路;当配置了Durable Objects时推荐使用
- ⚡ 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 Maps上传,使生产环境的堆栈跟踪显示可读代码。但它不会完成SDK初始化 — 你仍需要按照选项2完成SDK的实际设置。向导完成后,请继续执行选项2的SDK设置步骤。
注意: 与框架SDK(Next.js、SvelteKit)不同,目前没有针对Cloudflare的专属向导集成。向导仅处理Source Maps上传配置。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,
);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
生产环境:设置为Cloudflare密钥
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可让生产环境的堆栈跟踪显示可读代码。如果没有Source 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测试错误 — 请删除此代码");
},
} satisfies ExportedHandler<Env>,
);部署并触发该路由,然后检查你的Sentry问题面板 — 错误应该会在约30秒内显示。
验证清单:
| 检查项 | 验证方式 |
|---|---|
| 错误是否被捕获 | 在fetch处理器中抛出错误,在Sentry中查看是否显示 |
| 链路追踪是否正常 | 查看Performance面板中的HTTP链路 |
| Source Maps是否生效 | 检查堆栈跟踪是否显示可读的文件/行号 |
| D1查询链路是否正常(若配置) | 执行D1查询,查看是否存在 |
| 定时任务监控是否正常(若配置) | 触发定时任务,查看Crons面板 |
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日志功能 |
| | 自动检测 | 若未设置,会自动从 |
| | 自动检测 | 从 |
| | | 若未设置,会自动从 |
| | — | 若未设置,会自动从 |
| | — | 发送前过滤/修改错误事件 |
| | — | 发送前过滤/修改事务事件 |
| | — | 发送前过滤/修改日志条目 |
| | 所有URL | 控制哪些出站请求会添加追踪头 |
| | | 是否选择不启用OpenTelemetry兼容追踪器 |
| | | Durable Object:为原型方法添加监控以捕获RPC链路 |
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()| 集成 | 用途 |
|---|---|
| Prevent duplicate events (disabled for Workflows) |
| 按类型、消息、URL过滤事件 |
| 保留原始函数名 |
| 追踪错误中的 |
| 追踪出站 |
| 自动捕获Hono |
| 将请求数据附加到事件中 |
| 将 |
Phase 4: Cross-Link
阶段4:关联服务配置建议
After completing Cloudflare setup, check for companion services:
bash
undefined完成Cloudflare项目的Sentry设置后,检查是否存在关联服务:
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 |
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 事件未出现在Sentry中 | 未设置DSN或 | 临时在初始化选项中设置 |
| 缺少兼容性标志 | 在 |
| 堆栈跟踪显示混淆代码 | 未上传Source Maps | 配置 |
| 短生命周期请求中的事件丢失 | SDK在Worker终止前未完成事件发送 | 确保使用 |
| Hono错误未被捕获 | Hono应用未使用 | 将Hono应用作为第二个参数传递给 |
| Durable Object错误未被捕获 | 未为DO类添加监控 | 使用 |
| D1查询未创建链路 | 未为D1绑定添加监控 | 使用 |
| 定时处理器未被监控 | 未使用 | 确保 |
| 版本号未被自动检测 | 未配置 | 在 |
| Workflows中出现重复事件 | 去重集成过滤步骤失败 | SDK会自动为Workflows禁用去重集成;确保使用 |
| ", |