home / skills / andrelandgraf / fullstackrecipes / using-sentry

using-sentry skill

/.agents/skills/using-sentry

This skill helps you instrument applications with Sentry by capturing exceptions, adding context, tracing performance, and enabling structured logging.

npx playbooks add skill andrelandgraf/fullstackrecipes --skill using-sentry

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
2.9 KB
---
name: using-sentry
description: Capture exceptions, add context, create performance spans, and use structured logging with Sentry.
---

# Working with Sentry

Capture exceptions, add context, create performance spans, and use structured logging with Sentry.

## Implement Working with Sentry

Capture exceptions, add context, create performance spans, and use structured logging with Sentry.

**See:**

- Resource: `using-sentry` in Fullstack Recipes
- URL: https://fullstackrecipes.com/recipes/using-sentry

---

### Capturing Exceptions

Manually capture errors that are handled but should be tracked:

```typescript
import * as Sentry from "@sentry/nextjs";

try {
  await riskyOperation();
} catch (err) {
  Sentry.captureException(err);
  // Handle the error gracefully...
}
```

### Adding Context

Attach user and custom context to errors:

```typescript
import * as Sentry from "@sentry/nextjs";

// Set user context (persists for session)
Sentry.setUser({
  id: session.user.id,
  email: session.user.email,
});

// Add custom context to exceptions
Sentry.captureException(err, {
  tags: {
    feature: "checkout",
    plan: "pro",
  },
  extra: {
    orderId: "order_123",
    items: cart.items,
  },
});
```

### Performance Tracing

Create spans for meaningful operations:

```typescript
import * as Sentry from "@sentry/nextjs";

// Wrap async operations
const result = await Sentry.startSpan(
  {
    op: "http.client",
    name: "GET /api/users",
  },
  async () => {
    const response = await fetch("/api/users");
    return response.json();
  },
);

// Wrap sync operations
Sentry.startSpan(
  {
    op: "ui.click",
    name: "Submit Button Click",
  },
  (span) => {
    span.setAttribute("form", "checkout");
    processSubmit();
  },
);
```

### Using the Sentry Logger

Sentry provides structured logging that appears in the Logs tab:

```typescript
import * as Sentry from "@sentry/nextjs";

const { logger } = Sentry;

logger.info("Payment processed", { orderId: "123", amount: 99.99 });
logger.warn("Rate limit approaching", { current: 90, max: 100 });
logger.error("Payment failed", { orderId: "123", reason: "declined" });
```

### Breadcrumbs

Add breadcrumbs to provide context for errors:

```typescript
import * as Sentry from "@sentry/nextjs";

// Automatically captured: console logs, fetch requests, UI clicks
// Manual breadcrumbs for custom events:
Sentry.addBreadcrumb({
  category: "auth",
  message: "User signed in",
  level: "info",
});
```

### Clearing User Context

Clear user data on sign out:

```typescript
import * as Sentry from "@sentry/nextjs";

async function signOut() {
  Sentry.setUser(null);
  await authClient.signOut();
}
```

---

## References

- [Sentry Next.js SDK](https://docs.sentry.io/platforms/javascript/guides/nextjs/)
- [Custom Instrumentation](https://docs.sentry.io/platforms/javascript/guides/nextjs/tracing/instrumentation/custom-instrumentation/)

Overview

This skill shows how to integrate Sentry to capture exceptions, attach user and custom context, create performance spans, and emit structured logs and breadcrumbs. It provides practical TypeScript patterns for server and client Next.js code to improve observability and shorten debugging loops. The recipes focus on production-ready use: graceful error capture, meaningful traces, and clean user context handling.

How this skill works

The skill demonstrates manual exception capture with Sentry.captureException, setting persistent user/context using Sentry.setUser and tags/extra payloads, and adding breadcrumbs to record relevant user or system events. It also shows how to create synchronous and asynchronous performance spans via Sentry.startSpan and how to emit structured logs using Sentry.logger. Together these primitives feed Sentry’s Issues, Performance, and Logs views for faster root-cause analysis.

When to use it

  • Track handled errors that should still be visible to Sentry instead of being silently swallowed
  • Attach user identity and request-specific context for richer error and session correlation
  • Instrument slow or critical operations with spans for performance monitoring
  • Log structured events and warnings for operational visibility in the Logs view
  • Add breadcrumbs for user actions to reproduce steps leading to an error

Best practices

  • Capture errors deliberately where you handle them to avoid missing actionable failures
  • Attach minimal, relevant context (user id, order id, feature flag) to avoid PII exposure
  • Create spans around meaningful business operations, not every trivial function call
  • Use Sentry.logger for structured, searchable logs instead of console.log in production
  • Clear user context (Sentry.setUser(null)) on sign-out to prevent cross-session leakage

Example use cases

  • Wrap checkout flow API calls with spans and add orderId in extra so slow payments are correlated to Sentry Performance
  • Capture and tag known third-party failures to detect recurring integration issues
  • Add breadcrumbs for auth events (login, MFA) so support teams can trace account-state problems
  • Log payment warnings and errors with structured fields (orderId, amount, reason) to connect Logs and Issues
  • Set user context at session start so errors automatically include user id and email for faster triage

FAQ

When should I call Sentry.captureException vs letting errors bubble to Sentry automatically?

Call captureException for errors you catch and handle but still want tracked. Let uncaught exceptions propagate so automatic instrumentation captures them.

How much context should I attach to errors?

Attach minimal useful context: user id, correlation ids (orderId, requestId), and non-sensitive fields. Avoid storing raw PII or secrets in tags/extra.