Repository navigation
Expand file tree
/
Copy patherrorHandler.js
More file actions
506 lines (464 loc) · 16.4 KB
/
Copy patherrorHandler.js
File metadata and controls
506 lines (464 loc) · 16.4 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/**
* Centralised error handler middleware.
* Formats Horizon / Stellar SDK errors into consistent JSON responses.
* All non-Horizon errors are wrapped in StellarKitError for consistency.
*/
const logger = require("../utils/logger");
const { translateHorizonError } = require("../utils/horizonErrors");
const { mapHorizonErrorToStatus } = require("../utils/horizonStatusMapper");
const StellarKitError = require("../utils/StellarKitError");
const {
HORIZON_TIMEOUT_MESSAGE,
HORIZON_TIMEOUT_SUGGESTION,
isHorizonTimeoutError,
} = require("../utils/errors");
const { NETWORK } = require("../config/stellar");
const metrics = require("../services/metrics");
/**
* Returns true when the application is running in production mode.
* Used to gate whether internal error details are included in responses.
*/
function isProduction() {
return process.env.NODE_ENV === "production";
}
/**
* Strips internal implementation details from a message string when running
* in production. Removes:
* - Absolute file paths (Windows and POSIX)
* - Stack frame lines ("at SomeFunction (file:line:col)")
*
* In non-production environments the message is returned unchanged so
* developers see the full error text in development / test runs.
*
* @param {string} message - Raw error message that may contain internals.
* @param {string} [fallback="An unexpected error occurred."] - Safe fallback for production.
* @returns {string} Sanitised message.
*/
function sanitizeMessage(message, fallback = "An unexpected error occurred.") {
if (!isProduction()) return message;
if (!message || typeof message !== "string") return fallback;
// Strip Windows absolute paths (C:\...) and POSIX absolute paths (/...)
const hasFilePath = /([A-Za-z]:\\[^\s]+|\/[^\s]*\/[^\s]+)/.test(message);
// Strip stack frame lines produced by V8 (" at Foo (bar.js:1:2)")
const hasStackFrame = /^\s+at\s+/m.test(message);
if (hasFilePath || hasStackFrame) return fallback;
return message;
}
/**
* Logs 4xx and 5xx responses using the structured logger.
* Suppressed when NODE_ENV=test to keep test output clean.
*
* @param {number} status - HTTP status code
* @param {import('express').Request} req - Express request object
* @param {string} message - Human-readable error message
*/
function logError(status, req, message) {
if (process.env.NODE_ENV === "test") return;
if (status >= 400) {
const requestId = req.requestId || "-";
const logLevel = status >= 500 ? "error" : "warn";
logger[logLevel](
{
requestId,
method: req.method,
path: req.path,
status,
},
message
);
}
}
/**
* Send an error response AND record the status code in the metrics service.
* Also tracks the error per-endpoint (route + method combination).
*
* @param {import('express').Response} res
* @param {number} status
* @param {object} body
*/
function errorResponse(res, status, body) {
metrics.incrementError(status);
// Track error per endpoint (route + method combination)
const req = res.req;
if (req) {
const method = req.method;
// Use the Express matched route pattern when available so dynamic segments
// like /account/:id are grouped together rather than tracked per unique ID.
const routePattern = (req.route && req.route.path)
? (req.baseUrl || "") + req.route.path
: req.path;
metrics.incrementErrorByEndpoint(method, routePattern, status);
}
return res.status(status).json(body);
}
const ACCOUNT_MERGE_FAILURES = {
op_does_not_exist: {
message: "Account merge failed because the destination account does not exist.",
suggestion:
"Use an existing funded destination account (G...) before retrying the merge.",
},
op_malformed: {
message: "Account merge failed because the operation payload is malformed.",
suggestion:
"Check source/destination values and rebuild the transaction with a valid accountMerge operation.",
},
op_dest_full: {
message: "Account merge failed because the destination account cannot accept additional reserves or entries.",
suggestion:
"Free capacity on the destination account (remove subentries or use a different destination) and try again.",
},
};
/**
* Picks the most specific result code from Horizon's extras.result_codes.
* Prefers the transaction code, falling back to the first operation code.
*/
function pickMostSpecificResultCode(result_codes) {
if (!result_codes) return null;
if (typeof result_codes.transaction === "string") {
return result_codes.transaction;
}
if (Array.isArray(result_codes.operations) && result_codes.operations.length > 0) {
return result_codes.operations[0];
}
return null;
}
/**
* Returns true if the Horizon error is a transaction submission failure
* (i.e. the network accepted the request but the transaction itself failed).
*/
function isTransactionSubmissionFailure(horizonError) {
return (horizonError &&
horizonError.type &&
typeof horizonError.type === "string" &&
horizonError.type.includes("transaction_failed")
);
}
/**
* Returns true when err is a network-level connection failure to Horizon.
*/
function isConnectionError(err) {
if (!err) return false;
const code = err.code || (err.cause && err.cause.code);
if (code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "ECONNRESET") return true;
const msg = (err.message || "").toLowerCase();
return msg.includes("econnrefused") || msg.includes("enotfound");
}
/**
* Returns true when a Horizon 404 is for an offer endpoint
* (e.g. GET /offers/123 returned Not Found).
*/
function isOfferNotFoundError(err) {
if (!err || !err.response) return false;
const { status, config } = err.response;
if (status !== 404) return false;
const url = (config && config.url) || "";
return url.includes("/offers/");
}
/**
* Builds a normalised error body for a transaction submission failure.
*/
function buildTransactionSubmissionFailedError(horizonError) {
const resultCodes = horizonError.extras && horizonError.extras.result_codes
? horizonError.extras.result_codes
: {};
const resultCode = pickMostSpecificResultCode(resultCodes);
const humanMessage = resultCode ? translateHorizonError(resultCode) : null;
return {
type: "TransactionSubmissionFailed",
title: horizonError.title || "Transaction Failed",
detail: horizonError.detail || "The transaction was rejected by the Stellar network.",
message: humanMessage || horizonError.detail || "The transaction was rejected by the Stellar network.",
resultCodes,
...(resultCode ? { code: resultCode } : {}),
};
}
/**
* Injects requestId from the request into the response body.
*/
function withRequestId(body, req) {
return { ...body, requestId: req.requestId || null };
}
function errorHandler(err, req, res, next) {
if (isConnectionError(err)) {
const ske = new StellarKitError(
"Unable to connect to the Stellar Horizon node.",
503,
"HorizonUnavailable",
null,
"Check your HORIZON_URL and verify the node is reachable. See https://status.stellar.org for network status."
);
logError(503, req, ske.message);
return errorResponse(res, 503, withRequestId({
success: false,
error: ske.toJSON(),
}, req));
}
if (err?.isOfferNotFound || isOfferNotFoundError(err)) {
const offerId = err?.offerId || "unknown";
const message = `Offer '${offerId}' was not found on the Stellar ${NETWORK} network.`;
const ske = new StellarKitError(
message,
404,
"OfferNotFound",
null,
"The offer may have already been filled, cancelled, or the offer ID may be incorrect."
);
logError(404, req, ske.message);
return errorResponse(res, 404, withRequestId({
success: false,
error: ske.toJSON(),
}, req));
}
// Horizon errors returned from horizon-client / Stellar SDK
if (err && err.response && err.response.data) {
const horizonError = err.response.data;
const extras = horizonError.extras !== undefined ? horizonError.extras : null;
const resultCode = pickMostSpecificResultCode(horizonError?.extras?.result_codes);
// Handle op_low_reserve as a specific InsufficientReserve error
if (resultCode === "op_low_reserve") {
const status = mapHorizonErrorToStatus(resultCode) ?? 422;
const body = {
success: false,
error: {
type: "InsufficientReserve",
message: "Account does not have enough XLM to cover the minimum reserve requirement.",
suggestion: "Fund the account with additional XLM. Each account requires a base reserve of 1 XLM plus 0.5 XLM per subentry.",
},
};
logError(status, req, body.error.message);
return errorResponse(res, status, withRequestId(body, req));
}
const mappedStatus = mapHorizonErrorToStatus(resultCode);
const status = mappedStatus ?? err.response.status ?? 400;
if (isTransactionSubmissionFailure(horizonError)) {
const body = buildTransactionSubmissionFailedError(horizonError);
logError(status, req, body.message);
return errorResponse(res, status, withRequestId({ success: false, error: body }, req));
}
const message = horizonError.detail || horizonError.title || "Horizon Error";
const code = resultCode;
const humanMessage = code ? translateHorizonError(code) : null;
logError(status, req, message);
const body = {
success: false,
error: {
type: "HorizonError",
title: horizonError.title || "Horizon Error",
detail: message,
status: err.response.status,
extras,
},
};
if (code) {
body.error.code = code;
if (humanMessage && typeof humanMessage === "string" && humanMessage.length > 0) {
body.error.message = humanMessage;
}
}
return errorResponse(res, status, withRequestId(body, req));
}
// StellarKitError instances — already structured
if (err instanceof StellarKitError) {
logError(err.statusCode, req, err.message);
return errorResponse(res, err.statusCode, withRequestId({
success: false,
error: err.toJSON(),
}, req));
}
// ReferenceError and TypeError — catch runtime exceptions
if (err instanceof ReferenceError || err instanceof TypeError) {
logError(500, req, err.message);
return errorResponse(res, 500, withRequestId({
success: false,
error: {
type: "InternalError",
title: "Internal Server Error",
detail: sanitizeMessage(err.message),
},
}, req));
}
// Payload too large errors from body parsers
if (err.type === "entity.too.large" || err.status === 413) {
const maxBodySize = process.env.MAX_BODY_SIZE || "10kb";
const ske = new StellarKitError(
`Payload too large. Maximum request body size is ${maxBodySize}.`,
413,
"PayloadTooLargeError",
null,
`Reduce your request body size to under ${maxBodySize}.`
);
logError(413, req, ske.message);
return errorResponse(res, 413, withRequestId({
success: false,
error: ske.toJSON(),
}, req));
}
// AccountNotFound errors (Horizon 404 on account lookup)
// TransactionNotFound errors (Horizon 404 on transaction lookup)
if (err.isTransactionNotFound) {
logError(404, req, err.message);
return errorResponse(res, 404, withRequestId({
success: false,
error: {
type: "NotFound",
message: err.message,
suggestion: "Verify the transaction hash is correct and exists on the network.",
},
}, req));
}
// AccountNotFound errors (Horizon 404 on account lookup)
if (err.isAccountNotFound) {
logError(404, req, err.message);
return errorResponse(res, 404, withRequestId({
success: false,
error: {
type: "AccountNotFound",
message: err.message,
suggestion:
"Verify the account address is correct and that the account has been funded.",
},
}, req));
}
// AssetNotFound errors (asset lookup returned no results)
if (err.isAssetNotFound) {
logError(404, req, err.message);
return errorResponse(res, 404, withRequestId({
success: false,
error: {
type: "AssetNotFound",
message: err.message,
suggestion:
"Verify the asset code and issuer address are correct.",
},
}, req));
}
// TrustlineNotFound errors — specific asset trustline missing on an account
if (err.isTrustlineNotFound) {
logError(404, req, err.message);
return errorResponse(res, 404, withRequestId({
success: false,
error: {
type: "TrustlineNotFound",
message: err.message,
suggestion:
"The account must establish a trustline before holding this asset.",
},
}, req));
}
// LiquidityPoolNotFound errors (Horizon 404 on pool lookup)
if (err.isLiquidityPoolNotFound) {
logError(404, req, err.message);
return errorResponse(res, 404, withRequestId({
success: false,
error: {
type: "LiquidityPoolNotFound",
message: err.message,
suggestion:
"Verify the pool ID is correct and that the pool has not been dissolved.",
},
}, req));
}
// TomlFetchFailed errors — issuer's stellar.toml could not be fetched
// (network error, missing file, or invalid format)
if (err.isTomlFetchFailed) {
logError(502, req, err.message);
return errorResponse(res, 502, withRequestId({
success: false,
error: {
type: "TomlFetchFailed",
message: err.message,
suggestion:
"Verify the issuer has a valid stellar.toml at their home domain. See https://developers.stellar.org/docs/issuing-assets/publishing-asset-info for requirements.",
},
}, req));
}
// InvalidAsset errors — thrown by validateAsset(code, issuer)
if (err.isInvalidAsset) {
logError(400, req, err.message);
return errorResponse(res, 400, withRequestId({
success: false,
error: {
type: "InvalidAsset",
message: err.message,
suggestion: err.suggestion || undefined,
},
}, req));
}
// InvalidAccountId errors — thrown by validateAccountId(id)
if (err.isInvalidAccountId) {
logError(400, req, err.message);
return errorResponse(res, 400, withRequestId({
success: false,
error: {
type: "InvalidAccountId",
message: err.message,
suggestion: err.suggestion,
},
}, req));
}
// InvalidTransactionHash errors — thrown by validateTransactionHash(hash)
if (err.isInvalidTransactionHash) {
logError(400, req, err.message);
return errorResponse(res, 400, withRequestId({
success: false,
error: {
type: "InvalidTransactionHash",
message: err.message,
suggestion: err.suggestion,
},
}, req));
}
// HorizonTimeout errors — Horizon did not respond in time
if (isHorizonTimeoutError(err)) {
logError(504, req, HORIZON_TIMEOUT_MESSAGE);
return errorResponse(res, 504, withRequestId({
success: false,
error: {
type: "HorizonTimeout",
message: HORIZON_TIMEOUT_MESSAGE,
suggestion: HORIZON_TIMEOUT_SUGGESTION,
},
}, req));
}
// ValidationError — duck-typed validation failures (isValidation flag)
if (err.isValidation) {
logError(400, req, err.message);
return errorResponse(res, 400, withRequestId({
success: false,
error: {
type: "ValidationError",
message: err.message,
field: err.field,
receivedValue: err.receivedValue,
expectedFormat: err.expectedFormat,
suggestion: err.expectedFormat ? `Expected format: ${err.expectedFormat}` : undefined,
},
}, req));
}
// InsufficientXLMReserve — account lacks required XLM reserve
if (err.isInsufficientXLMReserve) {
const body = {
type: "ServerError",
message: err.message,
};
if (err.suggestion) body.suggestion = err.suggestion;
logError(500, req, err.message);
return errorResponse(res, 500, withRequestId({
success: false,
error: body,
}, req));
}
// Fallback for any other error
const status = err.status || err.statusCode || 500;
const message = sanitizeMessage(err.message || "Internal Server Error");
logError(status, req, err.message || "Internal Server Error");
return errorResponse(res, status, withRequestId({
success: false,
error: {
type: err.type || "ServerError",
message,
},
}, req));
}
// Export the middleware
module.exports = errorHandler;