@naturalcycles/backend-lib 9.77.1 → 9.77.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -2,6 +2,17 @@ import { _anyToError, _errorLikeToErrorObject } from '@naturalcycles/js-lib/erro
|
|
|
2
2
|
import { _objectAssign } from '@naturalcycles/js-lib/types';
|
|
3
3
|
const { APP_ENV } = process.env;
|
|
4
4
|
const includeErrorStack = APP_ENV === 'dev';
|
|
5
|
+
// Headers a handler may have set for the response it never got to send;
|
|
6
|
+
// they would wrongly describe the error response (e.g `res.json` keeps a pre-set Content-Type)
|
|
7
|
+
const staleResponseHeaders = [
|
|
8
|
+
'Content-Type',
|
|
9
|
+
'Content-Disposition',
|
|
10
|
+
'Content-Encoding',
|
|
11
|
+
'Content-Language',
|
|
12
|
+
'Content-Range',
|
|
13
|
+
'ETag',
|
|
14
|
+
'Last-Modified',
|
|
15
|
+
];
|
|
5
16
|
// Hacky way to store the errorService, so it's available to `respondWithError` function
|
|
6
17
|
let errorService;
|
|
7
18
|
let formatError;
|
|
@@ -14,17 +25,6 @@ export function genericErrorMiddleware(cfg = {}) {
|
|
|
14
25
|
errorService ||= cfg.errorReportingService;
|
|
15
26
|
formatError = cfg.formatError;
|
|
16
27
|
return (err, req, res, _next) => {
|
|
17
|
-
// if (res.headersSent) {
|
|
18
|
-
// Here we don't even log this error
|
|
19
|
-
// It's known that it comes from sentry.requestHandler()
|
|
20
|
-
// requestHandler waits for all promises/timeouts to finish in the request, and then emits this error here,
|
|
21
|
-
// while `res` is the same as was returned to the User (so, both headers and the data was already returned by that time)
|
|
22
|
-
// req.log.warn(`genericErrorHandler, but headersSent=true`, err)
|
|
23
|
-
// Here we don't propagate the error further, cause there's only "default express error logger" behind it
|
|
24
|
-
// and nothing else. Previously it was logging the same error once again because of this. Avoid.
|
|
25
|
-
// return next(err)
|
|
26
|
-
// return next()
|
|
27
|
-
// }
|
|
28
28
|
respondWithError(req, res, err);
|
|
29
29
|
};
|
|
30
30
|
}
|
|
@@ -48,34 +48,45 @@ export function respondWithError(req, res, err) {
|
|
|
48
48
|
// todo: add endpoint to the log
|
|
49
49
|
// todo: add userId from the "Context" (or, just req.userId?) to the log
|
|
50
50
|
}
|
|
51
|
-
if (headersSent)
|
|
51
|
+
if (headersSent) {
|
|
52
|
+
// Too late for an error response. A finished response needs nothing beyond the reporting above.
|
|
53
|
+
// An unfinished one (error mid-stream) is cut off, so the client sees a failed transfer right away
|
|
54
|
+
// instead of waiting for a body that never completes. Same as Express' default error handler.
|
|
55
|
+
if (!res.writableEnded)
|
|
56
|
+
res.destroy();
|
|
52
57
|
return;
|
|
58
|
+
}
|
|
53
59
|
const httpError = _errorLikeToErrorObject(originalError);
|
|
54
60
|
if (!includeErrorStack)
|
|
55
61
|
delete httpError.stack;
|
|
56
62
|
// http-errors (express itself, its body parsers) carry the status they should be answered with
|
|
57
|
-
|
|
63
|
+
const httpErrorLike = isHttpError(originalError) ? originalError : undefined;
|
|
64
|
+
httpError.data.backendResponseStatusCode ||= httpErrorLike?.statusCode || 500; // default to 500
|
|
58
65
|
_objectAssign(httpError.data, {
|
|
59
66
|
errorId,
|
|
60
67
|
headersSent: headersSent || undefined,
|
|
61
68
|
});
|
|
62
69
|
formatError?.(httpError, req); // Mutates the error
|
|
70
|
+
for (const header of staleResponseHeaders)
|
|
71
|
+
res.removeHeader(header);
|
|
72
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
73
|
+
if (httpErrorLike?.headers)
|
|
74
|
+
res.set(httpErrorLike.headers);
|
|
63
75
|
res.status(httpError.data.backendResponseStatusCode).json({
|
|
64
76
|
error: httpError,
|
|
65
77
|
});
|
|
66
78
|
}
|
|
67
79
|
/**
|
|
68
80
|
* Errors created by the `http-errors` package (express itself, body-parser, raw-body, send)
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
* (e.g a gateway's response
|
|
81
|
+
* describe the response they expect: `status` and `statusCode` (always equal),
|
|
82
|
+
* `expose` (whether the message is safe to show to the client) and optional response `headers`.
|
|
83
|
+
* The first three together are the marker: other libraries also put `statusCode` or `headers`
|
|
84
|
+
* on their errors (e.g a gateway's response), which say nothing about how we should respond.
|
|
73
85
|
*/
|
|
74
|
-
function
|
|
86
|
+
function isHttpError(err) {
|
|
75
87
|
const { status, statusCode, expose } = err;
|
|
76
|
-
if (typeof expose !== 'boolean' || typeof statusCode !== 'number' || status !== statusCode)
|
|
77
|
-
return;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
return statusCode;
|
|
88
|
+
if (typeof expose !== 'boolean' || typeof statusCode !== 'number' || status !== statusCode) {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
return Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599;
|
|
81
92
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { BackendErrorResponseObject, ErrorObject } from '@naturalcycles/js-lib/error'
|
|
2
2
|
import { _anyToError, _errorLikeToErrorObject } from '@naturalcycles/js-lib/error'
|
|
3
|
-
import type {
|
|
3
|
+
import type { StringMap } from '@naturalcycles/js-lib/types'
|
|
4
4
|
import { _objectAssign } from '@naturalcycles/js-lib/types'
|
|
5
5
|
import type { BackendErrorRequestHandler, BackendRequest, BackendResponse } from './server.model.js'
|
|
6
6
|
|
|
@@ -30,6 +30,18 @@ export interface ErrorReportingService {
|
|
|
30
30
|
const { APP_ENV } = process.env
|
|
31
31
|
const includeErrorStack = APP_ENV === 'dev'
|
|
32
32
|
|
|
33
|
+
// Headers a handler may have set for the response it never got to send;
|
|
34
|
+
// they would wrongly describe the error response (e.g `res.json` keeps a pre-set Content-Type)
|
|
35
|
+
const staleResponseHeaders = [
|
|
36
|
+
'Content-Type',
|
|
37
|
+
'Content-Disposition',
|
|
38
|
+
'Content-Encoding',
|
|
39
|
+
'Content-Language',
|
|
40
|
+
'Content-Range',
|
|
41
|
+
'ETag',
|
|
42
|
+
'Last-Modified',
|
|
43
|
+
]
|
|
44
|
+
|
|
33
45
|
// Hacky way to store the errorService, so it's available to `respondWithError` function
|
|
34
46
|
let errorService: ErrorReportingService | undefined
|
|
35
47
|
let formatError: GenericErrorMiddlewareCfg['formatError']
|
|
@@ -46,18 +58,6 @@ export function genericErrorMiddleware(
|
|
|
46
58
|
formatError = cfg.formatError
|
|
47
59
|
|
|
48
60
|
return (err, req, res, _next) => {
|
|
49
|
-
// if (res.headersSent) {
|
|
50
|
-
// Here we don't even log this error
|
|
51
|
-
// It's known that it comes from sentry.requestHandler()
|
|
52
|
-
// requestHandler waits for all promises/timeouts to finish in the request, and then emits this error here,
|
|
53
|
-
// while `res` is the same as was returned to the User (so, both headers and the data was already returned by that time)
|
|
54
|
-
// req.log.warn(`genericErrorHandler, but headersSent=true`, err)
|
|
55
|
-
// Here we don't propagate the error further, cause there's only "default express error logger" behind it
|
|
56
|
-
// and nothing else. Previously it was logging the same error once again because of this. Avoid.
|
|
57
|
-
// return next(err)
|
|
58
|
-
// return next()
|
|
59
|
-
// }
|
|
60
|
-
|
|
61
61
|
respondWithError(req, res, err)
|
|
62
62
|
}
|
|
63
63
|
}
|
|
@@ -85,13 +85,20 @@ export function respondWithError(req: BackendRequest, res: BackendResponse, err:
|
|
|
85
85
|
// todo: add userId from the "Context" (or, just req.userId?) to the log
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
-
if (headersSent)
|
|
88
|
+
if (headersSent) {
|
|
89
|
+
// Too late for an error response. A finished response needs nothing beyond the reporting above.
|
|
90
|
+
// An unfinished one (error mid-stream) is cut off, so the client sees a failed transfer right away
|
|
91
|
+
// instead of waiting for a body that never completes. Same as Express' default error handler.
|
|
92
|
+
if (!res.writableEnded) res.destroy()
|
|
93
|
+
return
|
|
94
|
+
}
|
|
89
95
|
|
|
90
96
|
const httpError = _errorLikeToErrorObject(originalError)
|
|
91
97
|
if (!includeErrorStack) delete httpError.stack
|
|
92
98
|
|
|
93
99
|
// http-errors (express itself, its body parsers) carry the status they should be answered with
|
|
94
|
-
|
|
100
|
+
const httpErrorLike = isHttpError(originalError) ? originalError : undefined
|
|
101
|
+
httpError.data.backendResponseStatusCode ||= httpErrorLike?.statusCode || 500 // default to 500
|
|
95
102
|
_objectAssign(httpError.data, {
|
|
96
103
|
errorId,
|
|
97
104
|
headersSent: headersSent || undefined,
|
|
@@ -99,27 +106,33 @@ export function respondWithError(req: BackendRequest, res: BackendResponse, err:
|
|
|
99
106
|
|
|
100
107
|
formatError?.(httpError, req) // Mutates the error
|
|
101
108
|
|
|
109
|
+
for (const header of staleResponseHeaders) res.removeHeader(header)
|
|
110
|
+
res.setHeader('Cache-Control', 'no-store')
|
|
111
|
+
if (httpErrorLike?.headers) res.set(httpErrorLike.headers)
|
|
112
|
+
|
|
102
113
|
res.status(httpError.data.backendResponseStatusCode).json({
|
|
103
114
|
error: httpError,
|
|
104
115
|
} satisfies BackendErrorResponseObject)
|
|
105
116
|
}
|
|
106
117
|
|
|
107
|
-
interface HttpErrorLike {
|
|
118
|
+
interface HttpErrorLike extends Error {
|
|
108
119
|
status: number
|
|
109
120
|
statusCode: number
|
|
110
121
|
expose: boolean
|
|
122
|
+
headers?: StringMap<string>
|
|
111
123
|
}
|
|
112
124
|
|
|
113
125
|
/**
|
|
114
126
|
* Errors created by the `http-errors` package (express itself, body-parser, raw-body, send)
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
* (e.g a gateway's response
|
|
127
|
+
* describe the response they expect: `status` and `statusCode` (always equal),
|
|
128
|
+
* `expose` (whether the message is safe to show to the client) and optional response `headers`.
|
|
129
|
+
* The first three together are the marker: other libraries also put `statusCode` or `headers`
|
|
130
|
+
* on their errors (e.g a gateway's response), which say nothing about how we should respond.
|
|
119
131
|
*/
|
|
120
|
-
function
|
|
132
|
+
function isHttpError(err: Error): err is HttpErrorLike {
|
|
121
133
|
const { status, statusCode, expose } = err as Partial<HttpErrorLike>
|
|
122
|
-
if (typeof expose !== 'boolean' || typeof statusCode !== 'number' || status !== statusCode)
|
|
123
|
-
|
|
124
|
-
|
|
134
|
+
if (typeof expose !== 'boolean' || typeof statusCode !== 'number' || status !== statusCode) {
|
|
135
|
+
return false
|
|
136
|
+
}
|
|
137
|
+
return Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599
|
|
125
138
|
}
|