error.ts
2.37 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
import { reportNetworkError } from './sentry';
/**
* 请求错误类
*/
export class RequestError extends Error {
code: string;
config: any;
request?: any;
response?: any;
isRequestError: boolean;
constructor(message: string, code: string, config: any, request?: any, response?: any) {
super(message);
this.name = 'RequestError';
this.code = code;
this.config = config;
this.request = request;
this.response = response;
this.isRequestError = true;
// 确保instanceof正常工作
Object.setPrototypeOf(this, RequestError.prototype);
// 如果配置中包含 sentryDsn,则上报错误到 Sentry
if (config && config.sentryDsn) {
this.reportToSentry();
}
}
/**
* 将错误上报到 Sentry
*/
reportToSentry(): void {
const errorInfo = {
code: this.code,
url: this.config?.url,
method: this.config?.method,
params: this.config?.params,
status: this.response?.status,
statusText: this.response?.statusText,
responseData: this.response?.data
};
reportNetworkError(this.message, errorInfo);
}
/**
* 创建网络错误
*/
static createNetworkError(message: string, config: any, request?: any): RequestError {
const error = new RequestError(
message || '网络错误',
'NETWORK_ERROR',
config,
request
);
return error;
}
/**
* 创建超时错误
*/
static createTimeoutError(config: any, request?: any): RequestError {
return new RequestError(
`请求超时: 超过了${config.timeout}ms`,
'TIMEOUT_ERROR',
config,
request
);
}
/**
* 创建取消错误
*/
static createCancelError(config: any, request?: any): RequestError {
return new RequestError(
'请求已被取消',
'CANCEL_ERROR',
config,
request
);
}
/**
* 创建服务器错误
*/
static createServerError(message: string, config: any, request?: any, response?: any): RequestError {
return new RequestError(
message || '服务器错误',
'SERVER_ERROR',
config,
request,
response
);
}
/**
* 创建请求错误
*/
static createRequestError(message: string, config: any, code = 'REQUEST_ERROR', request?: any): RequestError {
return new RequestError(
message,
code,
config,
request
);
}
}