跳到正文
cccskills
免费在 GitHub 公开

error-tracking

Add Sentry error reporting and performance monitoring to services, scheduled jobs, and database operations. Follow examples for capturing exceptions with useful context and measuring execution time through spans, which record individual operations for investigation.

中文简介正在准备中。当前显示英语简介。

原文查看原文说明

Add Sentry v8 error tracking and performance monitoring to your services. Use this skill when adding error handling, creating new controllers, instrumenting cron jobs, or tracking database performance. ALL ERRORS MUST BE CAPTURED TO SENTRY - no exceptions.

集成工具Sentry
查看安装方法

适用场景

  • Adding error reporting to an API
  • Recording failures and execution time for scheduled jobs
  • Measuring database and asynchronous operations
  • Testing whether errors reach Sentry

包含的文件(1)

  • SKILL.md9.2 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Sentry Integration Skill

Purpose

This skill enforces comprehensive Sentry error tracking and performance monitoring across all services following Sentry v8 patterns.

When to Use This Skill

  • Adding error handling to any code
  • Creating new controllers or routes
  • Instrumenting cron jobs
  • Tracking database performance
  • Adding performance spans
  • Handling workflow errors

🚨 CRITICAL RULE

ALL ERRORS MUST BE CAPTURED TO SENTRY - No exceptions. Never use console.error alone.

Current Status

Example: API Service ✅ Complete

  • Sentry v8 fully integrated
  • All workflow errors tracked
  • Background job processors instrumented
  • Test endpoints available

Sentry Integration Patterns

1. Controller Error Handling

// ✅ 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. Route Error Handling (Without 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. Workflow Error Handling

Example of a domain-specific Sentry helper from the original production project. If you build a helper like this for your domain, the call site looks like:

import { WorkflowSentryHelper } from '../workflow/utils/sentryHelper';

WorkflowSentryHelper.captureWorkflowError(error, {
    workflowCode: 'INVOICE_APPROVAL',
    instanceId: 123,
    stepId: 456,
    userId: 'user-123',
    operation: 'stepCompletion',
    metadata: { additionalInfo: 'value' }
});

Without a helper, plain Sentry works everywhere:

Sentry.captureException(error, {
    tags: { operation: 'stepCompletion' },
    extra: { workflowCode: 'INVOICE_APPROVAL', instanceId: 123, userId: 'user-123' }
});

4. Cron Jobs (MANDATORY Pattern)

#!/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. Database Performance Monitoring

Example from the original production project - a small helper that wraps DB calls in Sentry spans. Adapt to your codebase:

import { DatabasePerformanceMonitor } from '../utils/databasePerformance';

const result = await DatabasePerformanceMonitor.withPerformanceTracking(
    'findMany',
    'UserProfile',
    async () => {
        return await PrismaService.main.userProfile.findMany({
            take: 5,
        });
    }
);

The universally-available equivalent is a direct Sentry span:

const result = await Sentry.startSpan({
    name: 'db.userProfile.findMany',
    op: 'db.query',
    attributes: { 'db.model': 'UserProfile', 'db.operation': 'findMany' }
}, async () => {
    return await prisma.userProfile.findMany({ take: 5 });
});

6. Async Operations with Spans

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();
});

Error Levels

Use appropriate severity levels:

  • fatal: System is unusable (database down, critical service failure)
  • error: Operation failed, needs immediate attention
  • warning: Recoverable issues, degraded performance
  • info: Informational messages, successful operations
  • debug: Detailed debugging information (dev only)

Required Context

import * as Sentry from '@sentry/node';

Sentry.withScope((scope) => {
    // ALWAYS include these if available
    scope.setUser({ id: userId });
    scope.setTag('service', 'api'); // your service name
    scope.setTag('environment', process.env.NODE_ENV);

    // Add operation-specific context
    scope.setContext('operation', {
        type: 'workflow.start',
        workflowCode: 'INVOICE_APPROVAL',
        entityId: 123
    });

    Sentry.captureException(error);
});

Service Integration Examples

API Service (Example)

Location: ./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,
});

Key Helpers:

  • Custom Sentry helpers for domain-specific errors
  • DatabasePerformanceMonitor - DB query tracking
  • BaseController - Controller error handling

Notifications Service (Example)

Location: ./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,
});

Key Helpers:

  • Service-specific Sentry helpers for domain errors
  • BaseController - Controller error handling

Configuration (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

Testing Sentry Integration

Example Test Endpoints

# Test basic error capture
curl http://localhost:3000/api/sentry/test-error

# Test performance tracking
curl http://localhost:3000/api/sentry/test-performance

# Test database performance
curl http://localhost:3000/api/sentry/test-database-performance

Create test endpoints in your services to verify Sentry integration works end-to-end.

Performance Monitoring

Requirements

  1. All API endpoints must have transaction tracking
  2. Database queries > 100ms are automatically flagged
  3. N+1 queries are detected and reported
  4. Cron jobs must track execution time

Transaction Tracking

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();
}

Common Mistakes to Avoid

❌ NEVER use console.error without Sentry ❌ NEVER swallow errors silently ❌ NEVER expose sensitive data in error context ❌ NEVER use generic error messages without context ❌ NEVER skip error handling in async operations ❌ NEVER forget to import instrument.ts as first line in cron jobs

Implementation Checklist

When adding Sentry to new code:

  • Imported Sentry or appropriate helper
  • All try/catch blocks capture to Sentry
  • Added meaningful context to errors
  • Used appropriate error level
  • No sensitive data in error messages
  • Added performance tracking for slow operations
  • Tested error handling paths
  • For cron jobs: instrument.ts imported first

Key Files (Typical Structure)

Per Service

  • src/instrument.ts - Sentry initialization (imported first)
  • src/utils/sentryHelper.ts - Domain-specific error helpers
  • src/utils/databasePerformance.ts - DB monitoring
  • src/controllers/BaseController.ts - Controller base with Sentry

Configuration

  • config.ini or .env - Sentry DSN and settings
  • sentry.ini - Shared Sentry config (optional)

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Build Node.js, Express, and TypeScript APIs with consistent structure. Separate request handling, business logic, and database access, while following guidance for input validation, error tracking, configuration, and tests when adding features or refactoring existing services.

中文简介正在准备中。当前显示英语简介。

  • Adding an API endpoint
  • Separating business logic from database access
  • Standardizing input validation and error handling
diet103/claude-code-infrastructure-showcase1万2026年7月14日 更新

Build React and TypeScript pages with guidance for data fetching, loading states, styling, and navigation. Organize code by feature and apply lazy loading, which loads components when needed, using patterns for MUI v7 and TanStack Router/Query.

中文简介正在准备中。当前显示英语简介。

  • Creating a React page or component
  • Organizing frontend files by feature
  • Coordinating data fetching and loading states
diet103/claude-code-infrastructure-showcase1万2026年7月14日 更新

Create and maintain Claude Code skills with clear file structure and activation rules. Get guidance on hooks, which run at specific workflow events, plus troubleshooting, edit restrictions, and splitting detailed instructions into reference files.

中文简介正在准备中。当前显示英语简介。

  • Creating a new Claude Code skill
  • Tuning skill activation conditions
  • Investigating missing or unwanted activation
diet103/claude-code-infrastructure-showcase1万2026年7月14日 更新

Check a project's Codex infrastructure, fix missing dependencies, script permissions, and configuration errors, then repeat the check until failures are resolved. Receive a summary of repairs and any remaining optional-feature warnings.

中文简介正在准备中。当前显示英语简介。

  • Check the Codex environment after setup
  • Fix dependency and script permission errors
  • Repair JSON configuration syntax
diet103/claude-code-infrastructure-showcase1万2026年7月14日 更新

查看 diet103 的全部技能

报告此技能的问题