sentry.ts
7.85 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// 根据环境动态导入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('\x1b[32m✅ %s\x1b[0m', 'Sentry initialized successfully');
} catch (error) {
console.error('\x1b[31m❌ %s\x1b[0m', '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('\x1b[33m⚠️ %s\x1b[0m', '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('\x1b[31m❌ %s\x1b[0m', '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
};