-
Notifications
You must be signed in to change notification settings - Fork 400
Expand file tree
/
Copy pathpubnub-api-error.ts
More file actions
345 lines (312 loc) · 12.7 KB
/
pubnub-api-error.ts
File metadata and controls
345 lines (312 loc) · 12.7 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/**
* REST API endpoint use error module.
*
* @internal
*/
import { TransportResponse } from '../core/types/transport-response';
import RequestOperation from '../core/constants/operations';
import StatusCategory from '../core/constants/categories';
import { Payload, Status } from '../core/types/api';
import { PubNubError } from './pubnub-error';
/**
* PubNub REST API call error.
*
* @internal
*/
export class PubNubAPIError extends Error {
/**
* Construct API from known error object or {@link PubNub} service error response.
*
* @param errorOrResponse - `Error` or service error response object from which error information
* should be extracted.
* @param [data] - Preprocessed service error response.
*
* @returns `PubNubAPIError` object with known error category and additional information (if
* available).
*/
static create(errorOrResponse: Error | TransportResponse, data?: ArrayBuffer): PubNubAPIError {
if (PubNubAPIError.isErrorObject(errorOrResponse)) return PubNubAPIError.createFromError(errorOrResponse);
else return PubNubAPIError.createFromServiceResponse(errorOrResponse, data);
}
/**
* Create API error instance from other error object.
*
* @param error - `Error` object provided by network provider (mostly) or other {@link PubNub} client components.
*
* @returns `PubNubAPIError` object with known error category and additional information (if
* available).
*/
private static createFromError(error: unknown): PubNubAPIError {
let category: StatusCategory = StatusCategory.PNUnknownCategory;
let message = 'Unknown error';
let errorName = 'Error';
if (!error) return new PubNubAPIError(message, category, 0);
else if (error instanceof PubNubAPIError) return error;
if (PubNubAPIError.isErrorObject(error)) {
message = error.message;
errorName = error.name;
}
if (errorName === 'AbortError' || message.indexOf('Aborted') !== -1) {
category = StatusCategory.PNCancelledCategory;
message = 'Request cancelled';
} else if (message.toLowerCase().indexOf('timeout') !== -1) {
category = StatusCategory.PNTimeoutCategory;
message = 'Request timeout';
} else if (message.toLowerCase().indexOf('network') !== -1) {
category = StatusCategory.PNNetworkIssuesCategory;
message = 'Network issues';
} else if (errorName === 'TypeError') {
if (message.indexOf('Load failed') !== -1 || message.indexOf('Failed to fetch') != -1)
category = StatusCategory.PNNetworkIssuesCategory;
else category = StatusCategory.PNBadRequestCategory;
} else if (errorName === 'FetchError') {
const errorCode = (error as Record<string, string>).code;
if (['ECONNREFUSED', 'ENETUNREACH', 'ENOTFOUND', 'ECONNRESET', 'EAI_AGAIN'].includes(errorCode))
category = StatusCategory.PNNetworkIssuesCategory;
if (errorCode === 'ECONNREFUSED') message = 'Connection refused';
else if (errorCode === 'ENETUNREACH') message = 'Network not reachable';
else if (errorCode === 'ENOTFOUND') message = 'Server not found';
else if (errorCode === 'ECONNRESET') message = 'Connection reset by peer';
else if (errorCode === 'EAI_AGAIN') message = 'Name resolution error';
else if (errorCode === 'ETIMEDOUT') {
category = StatusCategory.PNTimeoutCategory;
message = 'Request timeout';
} else message = `Unknown system error: ${error}`;
} else if (message === 'Request timeout') category = StatusCategory.PNTimeoutCategory;
return new PubNubAPIError(message, category, 0, error as Error);
}
/**
* Construct API from known {@link PubNub} service error response.
*
* @param response - Service error response object from which error information should be
* extracted.
* @param [data] - Preprocessed service error response.
*
* @returns `PubNubAPIError` object with known error category and additional information (if
* available).
*/
private static createFromServiceResponse(response: TransportResponse, data?: ArrayBuffer): PubNubAPIError {
let category: StatusCategory = StatusCategory.PNUnknownCategory;
let errorData: Error | Payload | undefined;
let message = 'Unknown error';
let { status } = response;
data ??= response.body;
if (status === 402) message = 'Not available for used key set. Contact support@pubnub.com';
else if (status === 404) message = 'Resource not found';
else if (status === 400) {
category = StatusCategory.PNBadRequestCategory;
message = 'Bad request';
} else if (status === 403) {
category = StatusCategory.PNAccessDeniedCategory;
message = 'Access denied';
} else if (status >= 500) {
category = StatusCategory.PNServerErrorCategory;
message = 'Internal server error';
}
if (typeof response === 'object' && Object.keys(response).length === 0) {
category = StatusCategory.PNMalformedResponseCategory;
message = 'Malformed response (network issues)';
status = 400;
}
// Try to get more information about error from service response.
if (data && data.byteLength > 0) {
const decoded = new TextDecoder().decode(data);
if (
response.headers['content-type']!.indexOf('text/javascript') !== -1 ||
response.headers['content-type']!.indexOf('application/json') !== -1
) {
try {
const errorResponse: Payload = JSON.parse(decoded);
if (typeof errorResponse === 'object') {
if (!Array.isArray(errorResponse)) {
if (
'error' in errorResponse &&
(errorResponse.error === 1 || errorResponse.error === true) &&
'status' in errorResponse &&
typeof errorResponse.status === 'number' &&
'message' in errorResponse &&
'service' in errorResponse
) {
errorData = errorResponse;
status = errorResponse.status;
} else if (
'errors' in errorResponse &&
Array.isArray(errorResponse.errors) &&
errorResponse.errors.length > 0
) {
// Handle DataSync-style structured error responses:
// { errors: [{ errorCode: "SYN-0008", message: "...", path: "/id" }] }
errorData = errorResponse;
const errors = errorResponse.errors as Array<{
errorCode?: string;
message?: string;
path?: string;
}>;
message = errors
.map((e) => {
const parts: string[] = [];
if (e.errorCode) parts.push(e.errorCode);
if (e.message) parts.push(e.message);
return parts.join(': ');
})
.join('; ');
} else errorData = errorResponse;
if ('error' in errorResponse && errorResponse.error instanceof Error) errorData = errorResponse.error;
} else {
// Handling Publish API payload error.
if (typeof errorResponse[0] === 'number' && errorResponse[0] === 0) {
if (errorResponse.length > 1 && typeof errorResponse[1] === 'string') errorData = errorResponse[1];
}
}
}
} catch (_) {
errorData = decoded;
}
} else if (response.headers['content-type']!.indexOf('xml') !== -1) {
const reason = /<Message>(.*)<\/Message>/gi.exec(decoded);
message = reason ? `Upload to bucket failed: ${reason[1]}` : 'Upload to bucket failed.';
} else {
errorData = decoded;
}
}
return new PubNubAPIError(message, category, status, errorData);
}
/**
* Construct PubNub endpoint error.
*
* @param message - Short API call error description.
* @param category - Error category.
* @param statusCode - Response HTTP status code.
* @param [errorData] - Error information.
*/
constructor(
message: string,
public readonly category: StatusCategory,
public readonly statusCode: number,
public readonly errorData?: Error | Payload,
) {
super(message);
this.name = 'PubNubAPIError';
}
/**
* Convert API error object to API callback status object.
*
* @param operation - Request operation during which error happened.
*
* @returns Pre-formatted API callback status object.
*/
public toStatus(operation: RequestOperation): Status {
return {
error: true,
category: this.category,
operation,
statusCode: this.statusCode,
errorData: this.errorData,
// @ts-expect-error Inner helper for JSON.stringify.
toJSON: function (this: Status): string {
let normalizedErrorData: Payload | undefined;
const errorData = this.errorData;
if (errorData) {
try {
if (typeof errorData === 'object') {
const errorObject = {
...('name' in errorData ? { name: errorData.name } : {}),
...('message' in errorData ? { message: errorData.message } : {}),
...('stack' in errorData ? { stack: errorData.stack } : {}),
...errorData,
};
normalizedErrorData = JSON.parse(JSON.stringify(errorObject, PubNubAPIError.circularReplacer()));
} else normalizedErrorData = errorData;
} catch (_) {
normalizedErrorData = { error: 'Could not serialize the error object' };
}
}
// Make sure to exclude `toJSON` function from the final object.
const { toJSON, ...status } = this;
return JSON.stringify({ ...status, errorData: normalizedErrorData });
},
};
}
/**
* Format a user-facing error message for this API error.
*
* When the error contains structured details extracted from the service response
* (e.g., DataSync `errors` array), those details are included in the message.
* Otherwise, falls back to a generic description.
*
* @param operation - Request operation during which error happened.
*
* @returns Formatted error message string.
*/
public toFormattedMessage(operation: RequestOperation): string {
const fallback = 'REST API request processing error, check status for details';
// When errorData contains a structured `errors` array, `this.message` was already
// constructed from it in `createFromServiceResponse` — prefer it over the generic fallback.
if (
this.errorData &&
typeof this.errorData === 'object' &&
!('name' in this.errorData && 'message' in this.errorData && 'stack' in this.errorData) &&
'errors' in this.errorData &&
Array.isArray((this.errorData as Record<string, unknown>).errors)
) {
return `${operation}: ${this.message}`;
}
return fallback;
}
/**
* Convert API error object to PubNub client error object.
*
* @param operation - Request operation during which error happened.
* @param [message] - Custom error message.
*
* @returns Client-facing pre-formatted endpoint call error.
*/
public toPubNubError(operation: RequestOperation, message?: string): PubNubError {
return new PubNubError(message ?? this.message, this.toStatus(operation));
}
/**
* Function which handles circular references in serialized JSON.
*
* @returns Circular reference replacer function.
*
* @internal
*/
private static circularReplacer() {
const visited = new WeakSet();
return function (_: unknown, value: object | null) {
if (typeof value === 'object' && value !== null) {
if (visited.has(value)) return '[Circular]';
visited.add(value);
}
return value;
};
}
/**
* Check whether provided `object` is an `Error` or not.
*
* This check is required because the error object may be tied to a different execution context (global
* environment) and won't pass `instanceof Error` from the main window.
* To protect against monkey-patching, the `fetch` function is taken from an invisible `iframe` and, as a result,
* it is bind to the separate execution context. Errors generated by `fetch` won't pass the simple
* `instanceof Error` test.
*
* @param object - Object which should be checked.
*
* @returns `true` if `object` looks like an `Error` object.
*
* @internal
*/
private static isErrorObject(object: unknown): object is Error {
if (!object || typeof object !== 'object') return false;
if (object instanceof Error) return true;
if (
'name' in object &&
'message' in object &&
typeof object.name === 'string' &&
typeof object.message === 'string'
) {
return true;
}
return Object.prototype.toString.call(object) === '[object Error]';
}
}