sentry.js 6.13 KB
import sentryInit from "~/utils/sentryConfig/sentryInit";
const sentry = sentryInit();
/**
 * 通用 Sentry 错误上报方法
 * 1. 遍历参数对象的每一项,分别作为自定义参数上报
 * 2. 将整个对象 JSON.stringify 后作为特殊参数一起上报
 * @param {string} errorMessage - 错误信息
 * @param {Object} customParams - 自定义参数对象
 * @param {Object} options - 可选配置
 * @param {string} [options.errorType='general_error'] - 错误类型标签
 * @param {string} [options.level='error'] - 错误级别 (error, warning, info, debug)
 * @param {string} [options.fullObjectKey='full_params'] - 完整对象参数的键名
 * @param {Object} [options.tags] - 额外的标签对象
 * @param {Object} [options.contexts] - 额外的上下文对象
 */
function reportSentryError(errorMessage, customParams = {}, options = {}) {
  const {
    errorType = 'general_error',
    level = 'error',
    fullObjectKey = 'full_params',
    tags = {},
    contexts = {}
  } = options;

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

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

/**
 * 专门用于参数验证失败的错误上报
 * @param {string} errorMessage - 错误信息
 * @param {Object} params - 参数对象
 */
function reportParamError(errorMessage, params = {}) {
  return reportSentryError(errorMessage, params, {
    errorType: 'param_validation_error',
    level: 'warning',
    fullObjectKey: 'validation_full_params',
    tags: {
      category: 'validation'
    }
  });
}

/**
 * 用于 API 错误上报的专用方法
 * @param {string} errorMessage - 错误信息
 * @param {Object} apiParams - API 相关参数
 */
function reportApiError(errorMessage, apiParams = {}) {
  return reportSentryError(errorMessage, apiParams, {
    errorType: 'api_error',
    level: 'error',
    fullObjectKey: 'api_full_params',
    tags: {
      category: 'api'
    }
  });
}
module.exports = {
  reportSentryError,
  reportError,
  reportParamError,
  reportApiError,
  sentry
};

//## 使用示例:
// ### 1. 基本使用 - 传入任意参数对象
// const { reportSentryError } = require('../../utils/sentry');

// 用户信息相关错误
/* const userParams = {
  merchantId: this.data.merchantId,
  channelSource: this.data.channelSource,
  phone: this.data.phone,
  userId: this.data.userId,
  userInfo: this.data.userInfo
};

reportSentryError('用户信息获取失败', userParams, {
  errorType: 'user_info_error',
  level: 'warning'
});

// API 请求相关错误
const apiParams = {
  url: '/api/order/list',
  method: 'POST',
  requestData: { page: 1, size: 10 },
  responseCode: 500,
  responseMessage: 'Internal Server Error'
};

reportSentryError('API 请求失败', apiParams, {
  errorType: 'api_error',
  level: 'error',
  tags: {
    api_category: 'order',
    http_status: '500'
  }
}); */

// 简化使用

// 简单的错误上报
/*reportError('支付失败', {
  orderId: '12345',
  amount: 99.99,
  paymentMethod: 'wechat'
}); */

// const { reportParamError } = require('../../utils/sentry');

// 参数验证错误专用
/*const missingParams = {
  merchantId: this.data.merchantId,
  channelSource: this.data.channelSource,
  phone: this.data.phone,
  userInfo: this.data.userInfo
};

reportParamError('订单列表异常:merchantId, channelSource, phone 这三个参数有一个未获取到', missingParams); */

//复杂场景使用

// 购物车操作错误
/*const cartParams = {
  cartId: 'cart_123',
  productId: 'prod_456',
  quantity: 2,
  operation: 'add_to_cart',
  userAgent: wx.getDeviceInfo(),
  timestamp: Date.now()
};

reportSentryError('购物车操作失败', cartParams, {
  errorType: 'cart_operation_error',
  level: 'warning',
  tags: {
    operation_type: 'add_item',
    user_type: 'premium'
  },
  contexts: {
    device_info: { ...wx.getDeviceInfo(), ...wx.getWindowInfo(), ...wx.getAppBaseInfo() },
    app_version: '1.2.3'
  }
});*/