All files / services sentry.service.ts

0% Statements 0/77
0% Branches 0/1
0% Functions 0/1
0% Lines 0/77

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113                                                                                                                                                                                                                                 
import * as Sentry from '@sentry/node';
import { nodeProfilingIntegration } from '@sentry/profiling-node';
 
/**
 * 初始化 Sentry 错误监控
 */
export function initSentry() {
  const dsn = process.env.SENTRY_DSN;
  
  if (!dsn) {
    console.log('[Sentry] 未配置 SENTRY_DSN,错误监控已跳过');
    return false;
  }
 
  Sentry.init({
    dsn,
    environment: process.env.NODE_ENV || 'development',
    tracesSampleRate: process.env.NODE_ENV === 'production' ? 0.1 : 1.0,
    profilesSampleRate: 1.0,
    integrations: [
      nodeProfilingIntegration(),
    ],
    
    // 错误过滤
    beforeSend(event, hint) {
      // 过滤掉一些无关的错误
      const error = hint.originalException;
      if (error && typeof error === 'object' && 'message' in error) {
        const message = (error as Error).message;
        
        // 忽略一些常见的无关错误
        if (message.includes('ECONNREFUSED') && message.includes('Redis')) {
          return null;
        }
      }
      
      return event;
    },
  });
 
  console.log('[Sentry] 错误监控已初始化');
  return true;
}
 
/**
 * 捕获异常
 */
export function captureException(error: Error, context?: Record<string, any>) {
  Sentry.withScope((scope) => {
    if (context) {
      scope.setContext('extra', context);
    }
    Sentry.captureException(error);
  });
}
 
/**
 * 捕获消息
 */
export function captureMessage(message: string, level?: Sentry.SeverityLevel, context?: Record<string, any>) {
  Sentry.withScope((scope) => {
    if (level) {
      scope.setLevel(level);
    }
    if (context) {
      scope.setContext('extra', context);
    }
    Sentry.captureMessage(message);
  });
}
 
/**
 * 设置用户上下文
 */
export function setSentryUser(userId: number, email?: string) {
  Sentry.setUser({
    id: String(userId),
    email,
  });
}
 
/**
 * 设置标签
 */
export function setSentryTag(key: string, value: string) {
  Sentry.setTag(key, value);
}
 
/**
 * Koa 错误处理中间件
 */
export function sentryErrorHandler() {
  return async (ctx: any, next: any) => {
    try {
      await next();
    } catch (error) {
      if (error instanceof Error) {
        Sentry.withScope((scope) => {
          scope.setTag('method', ctx.method);
          scope.setTag('url', ctx.url);
          scope.setUser({
            id: ctx.state.user?.id ? String(ctx.state.user.id) : undefined,
          });
          Sentry.captureException(error);
        });
      }
      throw error;
    }
  };
}
 
export default Sentry;