sentry-demo.js
1.67 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
const { Request, Sentry } = require('../dist');
// 创建请求实例,并提供 Sentry DSN
const request = new Request({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 5000,
sentryDsn: 'https://examplePublicKey@o0.ingest.sentry.io/0', // 替换为实际的 Sentry DSN
sentryOptions: {
environment: 'development',
release: '1.0.0',
debug: true
}
});
// 发起一个正常请求
request.get('/posts/1')
.then(response => {
console.log('请求成功:', response.data);
})
.catch(error => {
console.error('请求失败:', error.message);
});
// 发起一个会失败的请求(用于演示错误上报)
request.get('/non-existent-endpoint')
.then(response => {
console.log('请求成功:', response.data);
})
.catch(error => {
console.error('请求失败:', error.message);
// 错误已自动上报到 Sentry
});
// 手动上报错误示例
setTimeout(() => {
try {
// 模拟一个业务逻辑错误
throw new Error('业务逻辑处理失败');
} catch (error) {
// 手动上报错误到 Sentry
Sentry.reportBusinessError(error.message, {
userId: '12345',
action: 'processData',
timestamp: new Date().toISOString()
});
console.error('业务错误已上报到 Sentry');
}
}, 1000);
// 参数验证错误示例
function validateUserData(userData) {
if (!userData.name) {
Sentry.reportValidationError('用户名不能为空', userData);
return false;
}
return true;
}
// 测试参数验证
const userData = { id: 1, email: 'test@example.com' }; // 缺少 name 字段
if (!validateUserData(userData)) {
console.error('用户数据验证失败,错误已上报到 Sentry');
}