SE

sentry-error-capture

Automates the implementation of advanced Sentry error tracking, context enrichment, and exception handling.

Install

mkdir -p .claude/skills/sentry-error-capture && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/5362" && unzip -o skill.zip -d .claude/skills/sentry-error-capture && rm skill.zip

Installs to .claude/skills/sentry-error-capture

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Implement advanced error capture and context enrichment with Sentry.
68 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Capture exceptions with full stack traces
  • Capture messages for non-exception events with severity levels
  • Enrich events with user identity, tags, and structured context
  • Add manual breadcrumbs to trace events leading to an error
  • Control issue grouping with custom fingerprinting
  • Filter events using beforeSend callbacks

How it works

This skill demonstrates how to capture exceptions and messages using Sentry SDKs, enriching them with scoped context like user data, tags, and extra information. It also covers adding breadcrumbs and customizing issue grouping with fingerprints.

Inputs & outputs

You give it
An error object, message string, or application event
You get back
An enriched error event or message sent to Sentry with associated context, tags, and breadcrumbs

When to use sentry-error-capture

  • Implementing captureException for errors
  • Adding user context to Sentry logs
  • Configuring custom error fingerprinting
  • Setting up Sentry breadcrumbs

About this skill

Sentry Error Capture

Overview

Capture errors and enrich them with structured context so your team can diagnose production issues in seconds instead of hours. Covers captureException, captureMessage, scoped context (withScope / push_scope), breadcrumbs, custom fingerprinting, and beforeSend filtering using @sentry/node v8 and sentry-sdk v2 APIs.

Prerequisites

  • Sentry SDK installed and initialized (@sentry/node v8+ or sentry-sdk v2+)
  • A valid DSN configured via environment variable (SENTRY_DSN)
  • Understanding of try/catch (JS) or try/except (Python) error handling
  • A Sentry project created at sentry.io

Instructions

Step 1 -- Capture Exceptions with Full Stack Traces

Always pass real Error objects (or Python exception instances), never plain strings. Plain strings lose the stack trace, making debugging far harder.

TypeScript (@sentry/node)

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

// CORRECT -- full stack trace preserved
try {
  await riskyOperation();
} catch (error) {
  Sentry.captureException(error);
}

// WRONG -- no stack trace, hard to debug
Sentry.captureException('something went wrong');

// Wrapping non-Error values into proper Error objects
Sentry.captureException(new Error(`API returned ${statusCode}: ${body}`));

// Capture with inline context (no scope needed for simple cases)
Sentry.captureException(error, {
  tags: { transaction: 'purchase' },
  extra: { orderId, amount },
});

Python (sentry-sdk)

import sentry_sdk

# CORRECT -- full traceback preserved
try:
    risky_operation()
except Exception as e:
    sentry_sdk.capture_exception(e)

# Capture current exception implicitly (inside except block)
try:
    risky_operation()
except Exception:
    sentry_sdk.capture_exception()  # captures sys.exc_info() automatically

Step 2 -- Capture Messages for Non-Exception Events

Use captureMessage for events that are not exceptions but still worth tracking: deprecation warnings, capacity thresholds, business logic anomalies.

TypeScript

// Severity levels: 'fatal' | 'error' | 'warning' | 'info' | 'debug' | 'log'
Sentry.captureMessage('Payment processed successfully', 'info');
Sentry.captureMessage('Deprecated API endpoint accessed', 'warning');
Sentry.captureMessage('Database connection pool exhausted', 'fatal');

Python

sentry_sdk.capture_message("Payment gateway timeout", level="warning")
sentry_sdk.capture_message("Daily report generated", level="info")
sentry_sdk.capture_message("Connection pool exhausted", level="fatal")

Step 3 -- Enrich Events with Scoped Context

Use withScope (TypeScript) or push_scope (Python) to attach context to a single event without polluting the global scope. Context is automatically cleaned up when the scope exits.

TypeScript -- withScope

Sentry.withScope((scope) => {
  // User identity for issue assignment and impact analysis
  scope.setUser({
    id: user.id,
    email: user.email,
    subscription: user.plan,
  });

  // Tags: indexed, searchable in Sentry UI filters
  scope.setTag('payment_provider', 'stripe');
  scope.setTag('feature', 'checkout');

  // Structured context: visible in event detail sidebar
  scope.setContext('payment', {
    amount: 9999,
    currency: 'USD',
    customer_id: 'cus_abc123',
    idempotency_key: 'idem_xyz789',
  });

  // Extra data: arbitrary key-value pairs for debugging
  scope.setExtra('cart', cartItems);

  // Override severity level
  scope.setLevel('fatal');

  // Custom fingerprint to control issue grouping
  scope.setFingerprint(['checkout-failure', paymentProvider]);

  Sentry.captureException(error);
});
// Scope is automatically cleaned up -- global scope unchanged

Python -- push_scope

with sentry_sdk.push_scope() as scope:
    scope.user = {"id": user_id, "email": user_email}
    scope.set_tag("feature", "checkout")
    scope.set_extra("cart", cart_items)
    scope.level = "fatal"
    scope.fingerprint = ["checkout-failure", str(error_code)]
    sentry_sdk.capture_exception(error)
# Scope is automatically cleaned up

Breadcrumbs

Breadcrumbs create a trail of events leading up to an error. Sentry auto-captures some (console logs, HTTP requests, DOM events), but manual breadcrumbs add domain-specific context.

TypeScript

Sentry.addBreadcrumb({
  category: 'auth',
  message: `User ${userId} logged in via ${provider}`,
  level: 'info',
  data: { provider, method: 'oauth2' },
});

Sentry.addBreadcrumb({
  category: 'transaction',
  message: 'Payment initiated',
  level: 'info',
  data: { amount: 49.99, items: 3 },
});
// The next captured error includes all breadcrumbs above

Python

sentry_sdk.add_breadcrumb(
    category="auth",
    message=f"User {user_id} logged in via {provider}",
    level="info",
    data={"provider": provider, "method": "oauth2"},
)

sentry_sdk.add_breadcrumb(
    category="transaction",
    message="Payment initiated",
    level="info",
    data={"amount": 49.99, "items": 3},
)

Custom Fingerprinting

Override Sentry's default grouping to control how errors are merged into issues. Without custom fingerprints, Sentry groups by stack trace, which can split logically identical errors or merge unrelated ones.

// Group all timeout errors for /api/search into one issue
Sentry.withScope((scope) => {
  scope.setFingerprint(['api-timeout', 'search-endpoint']);
  Sentry.captureException(new Error('Search API timeout'));
});

// Group by error type + HTTP status + endpoint
Sentry.withScope((scope) => {
  scope.setFingerprint(['http-error', String(response.status), endpoint]);
  Sentry.captureException(error);
});

// Use {{ default }} to extend rather than replace default grouping
Sentry.withScope((scope) => {
  scope.setFingerprint(['{{ default }}', tenantId]);
  Sentry.captureException(error);
});

Global Filtering with beforeSend

Configure beforeSend during initialization to filter noise, scrub sensitive data, or enrich all events globally.

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  beforeSend(event, hint) {
    const error = hint?.originalException;

    // Drop specific error types
    if (error instanceof AbortError) return null;
    if (error?.message?.match(/ResizeObserver loop/)) return null;

    // Scrub sensitive headers
    if (event.request?.headers) {
      delete event.request.headers['Authorization'];
      delete event.request.headers['Cookie'];
    }

    // Enrich database errors with subsystem tag
    if (error instanceof DatabaseError) {
      event.tags = { ...event.tags, subsystem: 'database' };
      event.level = 'fatal';
    }

    return event; // Must return event or null
  },

  // Pattern-based noise filtering
  ignoreErrors: [
    'ResizeObserver loop',
    'Non-Error promise rejection',
    /Loading chunk \d+ failed/,
    'Network request failed',
  ],
});

Output

  • Errors with full stack traces and context in the Sentry Issues dashboard
  • Scoped tags and structured context for filtering and search
  • Breadcrumb trails showing the user journey before errors
  • Custom fingerprints grouping related errors into single issues
  • Clean event stream via beforeSend filtering and ignoreErrors

Error Handling

ErrorCauseSolution
Missing stack traceString passed instead of Error objectAlways use new Error() or extend the Error class
Events not grouped properlyDefault fingerprinting insufficientUse scope.setFingerprint() with domain-specific keys
beforeSend dropping all eventsFunction returns undefinedAlways return event or explicitly null
Scope leaking between requestsGlobal scope modified in async contextUse withScope() / push_scope() for per-request context
Too many events hitting quotaNo filtering or sampling configuredAdd ignoreErrors, beforeSend filters, or sampleRate
Context not showing in Sentry UIUsed setExtra for structured dataUse setContext('name', {...}) for sidebar visibility

Examples

TypeScript -- Express Route with Context

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

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

app.get('/api/users/:id', async (req, res) => {
  Sentry.setUser({ id: req.params.id });
  try {
    const user = await getUser(req.params.id);
    res.json(user);
  } catch (error) {
    Sentry.withScope((scope) => {
      scope.setContext('request', {
        params: req.params,
        query: req.query,
        method: req.method,
      });
      Sentry.captureException(error);
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});

TypeScript -- Batch Processing with Promise.allSettled

async function processQueue(items: QueueItem[]) {
  const results = await Promise.allSettled(
    items.map(item => processItem(item))
  );
  results.forEach((result, index) => {
    if (result.status === 'rejected') {
      Sentry.withScope((scope) => {
        scope.setTag('queue_item_index', String(index));
        scope.setContext('item', items[index]);
        Sentry.captureException(result.reason);
      });
    }
  });
}

Python -- Background Job Error

import sentry_sdk

def process_report(report_id: str, user_id: str):
    sentry_sdk.add_breadcrumb(
        category="jobs",
        message=f"Report generation started: {report_id}",
        level="info",
    )
    try:
        data = fetch_report_data(report_id)
        return generate_pdf(data)
    except Exception as error:
        with sentry_sdk.push_scope() as scope:
            scope.user = {"id": user_id}
            scope.set_tag("job_type", "report_generation")
            scope.set_context("report", {
                "report_id": report_id,
             

---

*Content truncated.*

When not to use it

  • When basic error logging without context enrichment is sufficient
  • When performance tracing is the primary goal
  • When release management features are the main requirement

Prerequisites

Sentry SDK installed and initialized (@sentry/node v8+ or sentry-sdk v2+)A valid DSN configured via environment variable (SENTRY_DSN)Understanding of try/catch (JS) or try/except (Python) error handlingA Sentry project created at sentry.io

Limitations

  • Passing plain strings to captureException loses the stack trace
  • Context is automatically cleaned up when the scope exits
  • Sentry auto-captures some breadcrumbs, but manual ones add domain-specific context

How it compares

This approach provides detailed context and control over error reporting in Sentry, unlike basic error logging that only captures stack traces.

Compared to similar skills

sentry-error-capture side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
sentry-error-capture (this skill)127dReviewIntermediate
optimizing-performance12moReviewIntermediate
fireflies-debug-bundle127dCautionBeginner
sentry-debug-bundle127dCautionIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

optimizing-performance

CloudAI-X

Analyzes and optimizes application performance across frontend, backend, and database layers. Use when diagnosing slowness, improving load times, optimizing queries, reducing bundle size, or when asked about performance issues.

113

fireflies-debug-bundle

jeremylongshore

Collect Fireflies.ai debug evidence for support tickets and troubleshooting. Use when encountering persistent issues, preparing support tickets, or collecting diagnostic information for Fireflies.ai problems. Trigger with phrases like "fireflies debug", "fireflies support bundle", "collect fireflies logs", "fireflies diagnostic".

13

sentry-debug-bundle

jeremylongshore

Execute collect debug information for Sentry support tickets. Use when preparing support requests, debugging complex issues, or gathering diagnostic information. Trigger with phrases like "sentry debug info", "sentry support ticket", "gather sentry diagnostics", "sentry debug bundle".

13

logging-monitoring

jnPiyush

Implement observability patterns including structured logging, log levels, correlation IDs, metrics, and distributed tracing. Use when adding structured logging, implementing correlation IDs for request tracing, configuring metrics collection, setting up distributed tracing, or designing alerting ru

00

langfuse

davila7

Expert in Langfuse - the open-source LLM observability platform. Covers tracing, prompt management, evaluation, datasets, and integration with LangChain, LlamaIndex, and OpenAI. Essential for debugging, monitoring, and improving LLM applications in production. Use when: langfuse, llm observability, llm tracing, prompt management, llm evaluation.

743

sentry-rate-limits

jeremylongshore

Manage Sentry rate limits and quota optimization. Use when hitting rate limits, optimizing event volume, or managing Sentry costs. Trigger with phrases like "sentry rate limit", "sentry quota", "reduce sentry events", "sentry 429".

120

Search skills

Search the agent skills registry