Overview

Track errors and performance in production. Essential for debugging production issues.

Features

  • Error tracking
  • Performance monitoring
  • Release tracking
  • User context

Installation

npx hanma add sentry

Dependencies

@sentry/node

Code


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

/**
 * Initialize Sentry
 * Call this at the very beginning of your program, before any other imports!
 */
export const initSentry = () => {
  if (!process.env.SENTRY_DSN) {
    console.warn('[WARN] SENTRY_DSN not set, error tracking disabled');
    return;
  }

  Sentry.init({
    dsn: process.env.SENTRY_DSN,
    environment: process.env.NODE_ENV || 'development',
    release: process.env.npm_package_version,
    
    // Performance Monitoring
    tracesSampleRate: process.env.NODE_ENV === 'production' ? 0.1 : 1.0,
    
    // Only send errors in production
    enabled: process.env.NODE_ENV === 'production',

    // Add useful integrations for Express
    integrations: [
      // Sentry v8+ automatically adds many integrations
    ],
    
    // Filter sensitive data
    beforeSend(event) {
      if (event.request?.headers) {
        delete event.request.headers['authorization'];
        delete event.request.headers['cookie'];
        delete event.request.headers['x-api-key'];
      }
      return event;
    },
  });

  console.log('[OK] Sentry initialized');
};

/**
 * Setup Sentry error handler
 * Add this AFTER your routes, but BEFORE any other error handlers
 */
export const setupSentryErrorHandler = (app: Express) => {
  if (!process.env.SENTRY_DSN || process.env.NODE_ENV !== 'production') {
    return;
  }

  Sentry.setupExpressErrorHandler(app);
};

/**
 * Capture exception manually
 */
export const captureException = (error: Error, context?: Record<string, unknown>) => {
  Sentry.captureException(error, {
    extra: context,
  });
};

/**
 * Set user context for error tracking
 * Call this after user authentication
 */
export const setUser = (user: { id: string; email?: string; [key: string]: unknown }) => {
  Sentry.setUser(user);
};

/**
 * Clear user context (on logout)
 */
export const clearUser = () => {
  Sentry.setUser(null);
};

/**
 * Add breadcrumb for debugging
 */
export const addBreadcrumb = (message: string, category?: string, data?: Record<string, unknown>) => {
  Sentry.addBreadcrumb({
    message,
    category: category || 'custom',
    data,
    level: 'info',
  });
};

/**
 * Example usage in index.ts:
 * 
 * 1. Initialize first:
 * import { initSentry } from './libs/sentry';
 * initSentry();
 * 
 * 2. Setup app:
 * import express from 'express';
 * import { setupSentryErrorHandler } from './libs/sentry';
 * 
 * const app = express();
 * 
 * // Note: Request and Tracing handlers are now automatic in Sentry v8+ 
 * // if initSentry is called before app initialization.
 * 
 * // Your routes here
 * app.use('/api', routes);
 * 
 * // 3. Error handler (must be after routes)
 * setupSentryErrorHandler(app);
 * 
 * // Your custom error handler
 * app.use(errorHandler);
 */

Usage

import { initSentry, captureError } from './libs/sentry';

initSentry();

try { ... } catch (e) {
  captureError(e);
}

Dependencies

Frequently Asked Questions

How do I install Sentry Integration?
Run the following command: npx hanma add sentry
What dependencies are required?
This snippet requires: @sentry/node. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to libs/sentry.ts.
Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.