关于 error-tracking
error-tracking 是一项项目专用技能,用于落实 Sentry v8 错误跟踪与性能监控模式,指导开发者为服务、路由、工作流、定时任务和数据库操作添加监控。
主要功能
- 01使用 Sentry 捕获错误
- 02为错误报告添加上下文
- 03跟踪 API 和工作流性能
- 04监控数据库操作
- 05为定时任务添加监控
- 06遵循各服务的集成模式
适用场景
- 01为路由添加错误处理
- 02为工作流或定时任务添加监控
- 03跟踪耗时较长的数据库查询
- 04在多个服务中应用 Sentry 模式
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ jackspace/ claudeskillz --skill error-tracking安装后在 Claude Code 中输入/error-tracking确认已加载。
附带文件SKILL.json
详细介绍
项目 Sentry 集成技能
目的
此技能可按照 Sentry v8 模式,在项目的所有服务中全面启用 Sentry 错误追踪和性能监控。
何时使用此技能
- 为任何代码添加错误处理
- 创建新的控制器或路由
- 为定时任务添加监控
- 追踪数据库性能
- 添加性能 span
- 处理工作流错误
🚨 关键规则
所有错误都必须上报到 Sentry —— 不得例外。绝不能只使用 console.error。
当前状态
表单服务 ✅ 已完成
- 已全面集成 Sentry v8
- 已追踪所有工作流错误
- 已为 SystemActionQueueProcessor 添加监控
- 提供测试端点
邮件服务 🟡 进行中
- 已完成阶段 1-2(6/22 项任务)
- 仍有 189 处 ErrorLogger.log() 调用
Sentry 集成模式
1. 控制器错误处理
// ✅ CORRECT - Use BaseController
import { BaseController } from '../controllers/BaseController';
export class MyController extends BaseController {
async myMethod() {
try {
// ... your code
} catch (error) {
this.handleError(error, 'myMethod'); // Automatically sends to Sentry
}
}
}
2. 路由错误处理(不使用 BaseController)
import * as Sentry from '@sentry/node';
router.get('/route', async (req, res) => {
try {
// ... your code
} catch (error) {
Sentry.captureException(error, {
tags: { route: '/route', method: 'GET' },
extra: { userId: req.user?.id }
});
res.status(500).json({ error: 'Internal server error' });
}
});
3. 工作流错误处理
import { WorkflowSentryHelper } from '../workflow/utils/sentryHelper';
// ✅ CORRECT - Use WorkflowSentryHelper
WorkflowSentryHelper.captureWorkflowError(error, {
workflowCode: 'DHS_CLOSEOUT',
instanceId: 123,
stepId: 456,
userId: 'user-123',
operation: 'stepCompletion',
metadata: { additionalInfo: 'value' }
});
4. 定时任务(强制模式)
#!/usr/bin/env node
// FIRST LINE after shebang - CRITICAL!
import '../instrument';
import * as Sentry from '@sentry/node';
async function main() {
return await Sentry.startSpan({
name: 'cron.job-name',
op: 'cron',
attributes: {
'cron.job': 'job-name',
'cron.startTime': new Date().toISOString(),
}
}, async () => {
try {
// Your cron job logic
} catch (error) {
Sentry.captureException(error, {
tags: {
'cron.job': 'job-name',
'error.type': 'execution_error'
}
});
console.error('[Job] Error:', error);
process.exit(1);
}
});
}
main()
.then(() => {
console.log('[Job] Completed successfully');
process.exit(0);
})
.catch((error) => {
console.error('[Job] Fatal error:', error);
process.exit(1);
});
5. 数据库性能监控
import { DatabasePerformanceMonitor } from '../utils/databasePerformance';
// ✅ CORRECT - Wrap database operations
const result = await DatabasePerformanceMonitor.withPerformanceTracking(
'findMany',
'UserProfile',
async () => {
return await PrismaService.main.userProfile.findMany({
take: 5,
});
}
);
6. 使用 span 处理异步操作
import * as Sentry from '@sentry/node';
const result = await Sentry.startSpan({
name: 'operation.name',
op: 'operation.type',
attributes: {
'custom.attribute': 'value'
}
}, async () => {
// Your async operation
return await someAsyncOperation();
});
错误级别
使用适当的严重性级别:
- fatal:系统无法使用(数据库宕机、关键服务故障)
- error:操作失败,需要立即处理
- warning:可恢复的问题、性能下降
- info:信息性消息、成功的操作
- debug:详细的调试信息(仅限开发环境)
必需上下文
import * as Sentry from '@sentry/node';
Sentry.withScope((scope) => {
// ALWAYS include these if available
scope.setUser({ id: userId });
scope.setTag('service', 'form'); // or 'email', 'users', etc.
scope.setTag('environment', process.env.NODE_ENV);
// Add operation-specific context
scope.setContext('operation', {
type: 'workflow.start',
workflowCode: 'DHS_CLOSEOUT',
entityId: 123
});
Sentry.captureException(error);
});
特定服务的集成
表单服务
位置:./blog-api/src/instrument.ts
import * as Sentry from '@sentry/node';
import { nodeProfilingIntegration } from '@sentry/profiling-node';
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV || 'development',
integrations: [
nodeProfilingIntegration(),
],
tracesSampleRate: 0.1,
profilesSampleRate: 0.1,
});
主要辅助工具:
WorkflowSentryHelper- 工作流专用错误处理DatabasePerformanceMonitor- 数据库查询追踪BaseController- 控制器错误处理
邮件服务
位置:./notifications/src/instrument.ts
import * as Sentry from '@sentry/node';
import { nodeProfilingIntegration } from '@sentry/profiling-node';
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV || 'development',
integrations: [
nodeProfilingIntegration(),
],
tracesSampleRate: 0.1,
profilesSampleRate: 0.1,
});
主要辅助工具:
EmailSentryHelper- 邮件专用错误处理BaseController- 控制器错误处理
配置(config.ini)
[sentry]
dsn = your-sentry-dsn
environment = development
tracesSampleRate = 0.1
profilesSampleRate = 0.1
[databaseMonitoring]
enableDbTracing = true
slowQueryThreshold = 100
logDbQueries = false
dbErrorCapture = true
enableN1Detection = true
测试 Sentry 集成
表单服务测试端点
# Test basic error capture
curl http://localhost:3002/blog-api/api/sentry/test-error
# Test workflow error
curl http://localhost:3002/blog-api/api/sentry/test-workflow-error
# Test database performance
curl http://localhost:3002/blog-api/api/sentry/test-database-performance
# Test error boundary
curl http://localhost:3002/blog-api/api/sentry/test-error-boundary
邮件服务测试端点
# Test basic error capture
curl http://localhost:3003/notifications/api/sentry/test-error
# Test email-specific error
curl http://localhost:3003/notifications/api/sentry/test-email-error
# Test performance tracking
curl http://localhost:3003/notifications/api/sentry/test-performance
性能监控
要求
- 所有 API 端点都必须进行事务追踪
- 超过 100ms 的数据库查询会自动标记
- 会检测并报告 N+1 查询
- 定时任务必须追踪执行时间
事务追踪
import * as Sentry from '@sentry/node';
// Automatic transaction tracking for Express routes
app.use(Sentry.Handlers.requestHandler());
app.use(Sentry.Handlers.tracingHandler());
// Manual transaction for custom operations
const transaction = Sentry.startTransaction({
op: 'operation.type',
name: 'Operation Name',
});
try {
// Your operation
} finally {
transaction.finish();
}
应避免的常见错误
❌ 绝不要在未使用 Sentry 的情况下使用 console.error
❌ 绝不要悄无声息地吞掉错误
❌ 绝不要在错误上下文中暴露敏感数据
❌ 绝不要使用缺乏上下文的通用错误消息
❌ 绝不要跳过异步操作中的错误处理
❌ 绝不要忘记在定时任务中将 instrument.ts 作为第一行导入
实施检查清单
在新代码中添加 Sentry 时:
- 已导入 Sentry 或相应的辅助工具
- 所有 try/catch 块都会将错误上报到 Sentry
- 已为错误添加有意义的上下文
- 使用了适当的错误级别
- 错误消息中不包含敏感数据
- 已为耗时操作添加性能追踪
- 已测试错误处理路径
- 对于定时任务:首先导入 instrument.ts
关键文件
表单服务
/blog-api/src/instrument.ts- Sentry 初始化/blog-api/src/workflow/utils/sentryHelper.ts- 工作流错误/blog-api/src/utils/databasePerformance.ts- 数据库监控/blog-api/src/controllers/BaseController.ts- 控制器基类
邮件服务
/notifications/src/instrument.ts- Sentry 初始化/notifications/src/utils/EmailSentryHelper.ts- 邮件错误/notifications/src/controllers/BaseController.ts- 控制器基类
配置
/blog-api/config.ini- 表单服务配置/notifications/config.ini- 邮件服务配置/sentry.ini- 共享 Sentry 配置
文档
- 完整实现:
/dev/active/email-sentry-integration/ - 表单服务文档:
/blog-api/docs/sentry-integration.md - 邮件服务文档:
/notifications/docs/sentry-integration.md
相关技能
- 执行数据库操作前,使用 database-verification
- 获取工作流错误上下文时,使用 workflow-builder
- 处理数据库错误时,使用 database-scripts
评论
支持 Markdown