sentry.ts 7.74 KB
// 根据环境动态导入Sentry
import { detectEnvironment, EnvironmentType } from './utils';

// 预先导入可能使用的模块
import * as SentryBrowser from '@sentry/browser';
import { Sentry as SentryMiniapp } from './libs';

let Sentry: any;

// 使用环境检测函数选择合适的Sentry实现
const env = detectEnvironment();
if (env === EnvironmentType.MINIPROGRAM || env === EnvironmentType.UNIAPP) {
  // 小程序或uniapp环境
  Sentry = SentryMiniapp;
} else {
  // Web环境
  Sentry = SentryBrowser;
}

/**
 * Sentry 初始化配置
 */
let isInitialized = false;

/**
 * Sentry 初始化选项接口
 */
export interface SentryOptions {
  environment?: string;
  release?: string;
  debug?: boolean;
  tracesSampleRate?: number;
  attachStacktrace?: boolean;
  [key: string]: any;
}

/**
 * 错误上报选项接口
 */
export interface ErrorReportOptions {
  errorType?: string;
  level?: Sentry.SeverityLevel;
  fullObjectKey?: string;
  tags?: Record<string, string>;
  contexts?: Record<string, any>;
}

/**
 * 初始化 Sentry
 * @param dsn - Sentry DSN
 * @param options - 初始化选项
 */
function initSentry(dsn: string, options: SentryOptions = {}) {

  try {
    Sentry.init({
      dsn,
      // 默认配置
      tracesSampleRate: 1.0,
      // 合并用户配置
      ...options
    });
    
    isInitialized = true;
    console.log('Sentry initialized successfully');
  } catch (error) {
    console.error('Failed to initialize Sentry:', error);
  }
}

/**
 * 检查 Sentry 是否已初始化
 * @returns {boolean} 是否已初始化
 */
function isSentryInitialized() {
  return isInitialized;
}

/**
 * 通用 Sentry 错误上报方法
 * 1. 遍历参数对象的每一项,分别作为自定义参数上报
 * 2. 将整个对象 JSON.stringify 后作为特殊参数一起上报
 * @param errorMessage - 错误信息
 * @param customParams - 自定义参数对象
 * @param options - 可选配置
 */
function reportSentryError(errorMessage: string, customParams: Record<string, any> = {}, options: ErrorReportOptions = {}) {
  if (!isInitialized) {
    console.warn('Sentry is not initialized. Error not reported:', errorMessage);
    return;
  }

  const {
    errorType = 'general_error',
    level = 'error',
    fullObjectKey = 'full_params',
    tags = {},
    contexts = {}
  } = options;

  try {
    // 第一步:遍历参数对象的每一项,分别作为自定义参数上报
    Object.keys(customParams).forEach(key => {
      const value = customParams[key];
      
      // 如果值是对象,转换为 JSON 字符串
      const processedValue = typeof value === 'object' && value !== null 
        ? JSON.stringify(value) 
        : value;
      
      // 设置为上下文信息(每个参数单独设置)
      Sentry.setContext(key, {
        value: processedValue,
        originalType: typeof value,
        timestamp: new Date().toISOString()
      });
    });
    
    // 第二步:将整个对象 JSON.stringify 后作为特殊参数上报
    const fullObjectString = JSON.stringify(customParams);
    Sentry.setContext(fullObjectKey, {
      data: fullObjectString,
      type: 'full_object',
      size: fullObjectString.length,
      timestamp: new Date().toISOString()
    });
    
    // 如果完整对象字符串不太长,也设置为用户属性
    if (fullObjectString.length <= 1000) {
      Sentry.setUser({
        [fullObjectKey]: fullObjectString
      });
    }
    
    // 设置错误类型标签
    Sentry.setTag('error_type', errorType);
    
    // 设置参数统计标签
    Sentry.setTag('params_count', String(Object.keys(customParams).length));
    Sentry.setTag('full_object_size', fullObjectString.length > 1000 ? 'large' : 'normal');
    
    // 设置额外的标签
    Object.keys(tags).forEach(tagKey => {
      Sentry.setTag(tagKey, String(tags[tagKey]));
    });
    
    // 设置额外的上下文
    Object.keys(contexts).forEach(contextKey => {
      Sentry.setContext(contextKey, contexts[contextKey]);
    });
    
    // 设置错误级别 - 使用 configureScope 设置级别
    Sentry.withScope((scope: any) => {
      scope.setLevel(level);
    });
    
    // 上报错误
    Sentry.captureException(new Error(errorMessage));
  } catch (error) {
    console.error('Sentry 错误上报失败:', error);
  }
}

/**
 * 简化版本 - 只设置自定义参数和基本错误信息
 * @param errorMessage - 错误信息
 * @param customParams - 自定义参数对象
 * @param level - 错误级别
 */
function reportError(errorMessage: string, customParams: Record<string, any> = {}, level: Sentry.SeverityLevel = 'error') {
  return reportSentryError(errorMessage, customParams, { level });
}

/**
 * 专门用于参数验证失败的错误上报
 * @param errorMessage - 错误信息
 * @param params - 参数对象
 */
function reportValidationError(errorMessage: string, params: Record<string, any> = {}) {
  return reportSentryError(errorMessage, params, {
    errorType: 'validation_error',
    level: 'warning'
  });
}

/**
 * 专门用于网络请求错误的上报
 * @param errorMessage - 错误信息
 * @param requestInfo - 请求信息
 */
function reportNetworkError(errorMessage: string, requestInfo: Record<string, any> = {}) {
  return reportSentryError(errorMessage, requestInfo, {
    errorType: 'network_error',
    fullObjectKey: 'request_info'
  });
}

/**
 * 专门用于业务逻辑错误的上报
 * @param errorMessage - 错误信息
 * @param businessData - 业务数据
 * @param extraInfo - 额外信息,如请求上下文、环境信息等
 * @param options - 错误上报选项,如错误级别、标签等
 */
function reportBusinessError(
  errorMessage: string, 
  businessData: Record<string, any> = {}, 
  extraInfo: Record<string, any> = {},
  options: Partial<ErrorReportOptions> = {}
) {
  // 合并业务数据和额外信息
  const enrichedData = {
    ...businessData,
    
    // 请求上下文信息
    requestContext: extraInfo.requestContext || {},
    
    // 环境信息
    environment: {
      timestamp: new Date().toISOString(),
      userAgent: extraInfo.userAgent || (typeof navigator !== 'undefined' ? navigator.userAgent : 'unknown'),
      platform: extraInfo.platform || (typeof navigator !== 'undefined' ? navigator.platform : 'unknown'),
      screenSize: extraInfo.screenSize || (typeof window !== 'undefined' ? `${window.innerWidth}x${window.innerHeight}` : 'unknown'),
      appVersion: extraInfo.appVersion || (typeof navigator !== 'undefined' ? navigator.appVersion : 'unknown'),
      ...extraInfo.environment
    },
    
    // 错误上下文
    errorContext: {
      code: businessData.code || extraInfo.code,
      type: businessData.type || extraInfo.type || 'business_error',
      ...extraInfo.errorContext
    }
  };
  
  // 默认错误级别根据业务错误码确定
  const errorLevel = options.level || getErrorLevelByCode(businessData.code);
  
  return reportSentryError(errorMessage, enrichedData, {
    errorType: 'business_error',
    fullObjectKey: 'business_data',
    level: errorLevel,
    tags: {
      errorCode: String(businessData.code || 'unknown'),
      ...options.tags
    },
    contexts: options.contexts
  });
}

/**
 * 根据错误码确定错误级别
 * @param code - 错误码
 * @returns Sentry错误级别
 */
function getErrorLevelByCode(code: string | number): Sentry.SeverityLevel {
  if (!code) return 'error';
  
  const codeNum = Number(code);
  
  // 根据错误码范围确定错误级别
  if (codeNum >= 500) return 'error';     // 服务器错误
  if (codeNum >= 400) return 'warning';   // 客户端错误
  if (codeNum >= 300) return 'info';      // 重定向
  
  return 'error'; // 默认为错误级别
}

export {
  initSentry,
  isSentryInitialized,
  reportSentryError,
  reportError,
  reportValidationError,
  reportNetworkError,
  reportBusinessError
};