Index of every page on this site: llms.txt
All skills
jeremylongshore avatar

/sentry-sdk-patterns

@0d57af8
Run it yourself

Best practices for using Sentry SDK in TypeScript and Python. Use when implementing structured error context with scopes, breadcrumb strategies, beforeSend/beforeBreadcrumb filtering, custom fingerprinting, user context, or performance span creation. Trigger: "sentry best practices", "sentry patterns", "sentry sdk usage", "sentry scope", "sentry breadcrumbs", "sentry beforeSend", "sentry fingerprint".

Use this Skill: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/sentry-sdk-patterns

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesimplementation.md

≈1.4k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Implementation Guide

Pattern Checklist

  1. Create a centralized error handler module wrapping Sentry.withScope() / sentry_sdk.new_scope()
  2. Implement structured breadcrumb helpers by category (auth, db, http, business)
  3. Configure beforeSend to drop non-actionable errors and scrub PII
  4. Configure beforeBreadcrumb to redact sensitive data from breadcrumb payloads
  5. Set custom fingerprints for error classes where stack-trace grouping is insufficient
  6. Implement framework error boundaries (Express middleware, React withErrorBoundary)
  7. Add performance spans for critical code paths using Sentry.startSpan()
  8. Mock Sentry in tests to verify context is attached correctly

Pattern 1: Centralized Error Handler (TypeScript)

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

export function captureError(
  error: Error,
  context?: Record<string, unknown>
): string {
  return Sentry.captureException(error, {
    extra: context,
    tags: { handler: 'centralized' },
  });
}

export function captureWarning(
  message: string,
  context?: Record<string, unknown>
): void {
  Sentry.captureMessage(message, {
    level: 'warning',
    extra: context,
  });
}

Pattern 2: Scoped Context (TypeScript)

Sentry.withScope((scope) => {
  scope.setTag('module', 'payments');
  scope.setLevel('error');
  scope.setContext('order', { id: orderId, total: amount });
  scope.setUser({ id: userId });
  scope.setFingerprint(['payment-failure', gatewayName]);
  Sentry.captureException(error);
});

Pattern 3: beforeSend Filter (TypeScript)

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  beforeSend(event, hint) {
    const error = hint?.originalException;
    if (error instanceof Error) {
      if (error.message.includes('ResizeObserver loop')) return null;
      if (error.message.includes('Network request failed')) return null;
    }
    if (event.user) {
      delete event.user.ip_address;
      delete event.user.email;
    }
    return event;
  },
});

Pattern 4: Structured Breadcrumbs (TypeScript)

Sentry.addBreadcrumb({
  category: 'payment',
  message: `Processing payment of $${amount}`,
  level: 'info',
  data: { userId, amount, gateway: 'stripe' },
});

try {
  await processPayment(userId, amount);
} catch (error) {
  Sentry.captureException(error);
  // Breadcrumbs above will appear in the event timeline
}

Pattern 5: Performance Spans (TypeScript)

async function processOrder(orderId: string) {
  return Sentry.startSpan(
    { name: 'processOrder', op: 'task', attributes: { orderId } },
    async (span) => {
      const order = await Sentry.startSpan(
        { name: 'db.getOrder', op: 'db.query' },
        () => db.orders.findById(orderId),
      );
      await Sentry.startSpan(
        { name: 'payment.charge', op: 'http.client' },
        () => chargePayment(order),
      );
      span.setStatus({ code: 1, message: 'ok' });
      return order;
    },
  );
}

Pattern 6: Python Decorator for Spans

import sentry_sdk
from functools import wraps

def sentry_traced(op="function"):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            with sentry_sdk.start_span(op=op, name=func.__name__):
                return func(*args, **kwargs)
        return wrapper
    return decorator

@sentry_traced(op="db.query")
def get_user(user_id: str):
    return db.users.find_one({"_id": user_id})

Pattern 7: Express Error Middleware (Sentry v8)

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

const app = express();
Sentry.setupExpressErrorHandler(app);

app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
  Sentry.withScope((scope) => {
    scope.setContext('request', {
      method: req.method,
      url: req.originalUrl,
      params: req.params,
    });
    Sentry.captureException(err);
  });
  res.status(500).json({ error: 'Internal server error' });
});

Pattern 8: Django Middleware (Python)

import sentry_sdk

class SentryUserMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if hasattr(request, "user") and request.user.is_authenticated:
            sentry_sdk.set_user({
                "id": str(request.user.id),
                "email": request.user.email,
                "username": request.user.username,
            })
        response = self.get_response(request)
        return response

Pattern 9: Testing Sentry Integration (Vitest)

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

vi.mock('@sentry/node', () => ({
  captureException: vi.fn(),
  captureMessage: vi.fn(),
  withScope: vi.fn((cb) =>
    cb({
      setTag: vi.fn(),
      setContext: vi.fn(),
      setUser: vi.fn(),
      setLevel: vi.fn(),
      setFingerprint: vi.fn(),
    }),
  ),
  addBreadcrumb: vi.fn(),
  setUser: vi.fn(),
  setTag: vi.fn(),
  startSpan: vi.fn((opts, cb) => cb({ setStatus: vi.fn() })),
}));

it('captures payment errors with correct context', async () => {
  await processPayment({ amount: -1 });
  expect(Sentry.captureException).toHaveBeenCalledWith(
    expect.objectContaining({
      message: expect.stringContaining('Invalid amount'),
    }),
  );
});

Tons of Skills by Intent Solutions | jeremylongshore.com

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts2mo3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    The skill provides standard developer guidance for using Sentry SDKs in TypeScript and Python, including error handling, performance spans, and PII scrubbing. No security risks were identified.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at 0d57af8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated 3 months ago
What it can do
Reads files Edits files
version
1.51.0
author
Jeremy Longshore <jeremy@intentsolutions.io>
compatibility
Designed for Claude Code
All 4 allowed tools
ReadWriteEditGrep
Other metadata
tags
[
  "saas",
  "sentry",
  "python",
  "typescript",
  "best-practices",
  "error-handling"
]

README badge

README badge for jeremylongshore/tons-of-skills-marketplace/sentry-sdk-patterns