优化 环境控制,错误监控只在生产环境启用

This commit is contained in:
yuantao
2025-12-01 14:44:29 +08:00
parent bfcf289acb
commit 328a53a343
3 changed files with 84 additions and 4 deletions

View File

@@ -371,6 +371,44 @@ class Tool {
})
}
/**
* 检测是否为生产环境
* @private
* @returns {boolean} 是否为生产环境
*/
_isProduction() {
// 检查uniapp运行模式
try {
const systemInfo = uni.getSystemInfoSync?.()
if (systemInfo?.mode && systemInfo.mode !== 'default') {
// 体验版、开发版、预览版
return false
}
} catch (error) {
// 忽略错误,继续检测
}
// 检查环境变量MODE
if (import.meta.env.MODE === 'development') {
return false
}
// 检查自定义环境变量
const enableProductionMode = import.meta.env.VITE_ENABLE_ERROR_MONITOR === 'true'
const disableProductionMode = import.meta.env.VITE_DISABLE_ERROR_MONITOR === 'true'
if (disableProductionMode) {
return false
}
if (enableProductionMode) {
return true
}
// 默认:开发环境和体验版不启用,生产环境启用
return true
}
/**
* 初始化全局错误监控
* @param {Object} options 配置选项
@@ -380,6 +418,7 @@ class Tool {
* @param {string} [options.webhookUrl] 自定义webhook地址不传则使用环境变量
* @param {number} [options.maxRetries=3] 发送失败时最大重试次数
* @param {number} [options.retryDelay=1000] 重试延迟时间(毫秒)
* @param {boolean} [options.forceEnable=false] 强制启用错误监控(忽略环境检查)
*/
initErrorMonitor(options = {}) {
const config = {
@@ -389,9 +428,16 @@ class Tool {
webhookUrl: import.meta.env.VITE_WEBHOOK,
maxRetries: 3,
retryDelay: 1000,
forceEnable: false,
...options,
}
// 环境检查:只在生产环境下启用错误监控
if (!config.forceEnable && !this._isProduction()) {
console.info('当前为非生产环境,错误监控已禁用')
return
}
// 检查webhook配置
if (!config.webhookUrl) {
console.warn('错误监控初始化失败未配置webhook地址')
@@ -506,8 +552,9 @@ class Tool {
* 手动上报错误
* @param {Error|Object} error 错误对象或错误信息
* @param {Object} [context] 错误上下文信息
* @param {boolean} [forceSend=false] 强制发送(忽略环境检查)
*/
reportError(error, context = {}) {
reportError(error, context = {}, forceSend = false) {
const errorInfo = {
type: 'manual',
error: error instanceof Error ? error.message : error,
@@ -519,7 +566,12 @@ class Tool {
page: getCurrentPageName(),
}
this._sendErrorToWebhook(errorInfo)
if (forceSend) {
// 强制发送
this._sendErrorToWebhook(errorInfo, 0, true)
} else {
this._sendErrorToWebhook(errorInfo)
}
}
/**
@@ -539,10 +591,25 @@ class Tool {
global: 0,
promise: 0,
console: 0,
miniProgram: 0,
lastErrorTime: null,
}
}
/**
* 获取当前环境信息
* @returns {Object} 环境信息
*/
getEnvironmentInfo() {
return {
isProduction: this._isProduction(),
mode: import.meta.env.MODE,
platform: this._getUserAgent(),
errorMonitorEnabled: !!this.config,
timestamp: Date.now(),
}
}
/**
* 处理全局错误
* @private
@@ -706,7 +773,13 @@ class Tool {
* 发送错误到webhook
* @private
*/
async _sendErrorToWebhook(errorInfo, retryCount = 0) {
async _sendErrorToWebhook(errorInfo, retryCount = 0, forceSend = false) {
// 环境检查:只在生产环境下发送错误信息
if (!forceSend && !this._isProduction() && !this.config?.forceEnable) {
console.info('非生产环境错误信息不上报到webhook:', errorInfo.type)
return
}
const webhookUrl = import.meta.env.VITE_WEBHOOK
if (!webhookUrl) {
console.error('未配置webhook地址无法发送错误信息')