-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy patherror-messenger.js
More file actions
49 lines (44 loc) · 2.23 KB
/
error-messenger.js
File metadata and controls
49 lines (44 loc) · 2.23 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
/**
* Errors from RERUM are a response code with a text body (except those handled specifically upstream)
* We want to send the same error code and message through. It is assumed to be RESTful and useful.
* This is a fallback for unhandled errors from RERUM, and should not be used for expected errors that are handled upstream (e.g. 409 conflict for version mismatch on overwrite). It will also handle network errors that occur when trying to reach RERUM, which will be mapped to a 502 Bad Gateway with a message indicating a RERUM network error.
* This will also handle generic (500) app level errors, as well as app level 404 errors.
*
* @param rerum_error_res A Fetch API Response object from a fetch() to RERUM that encountered an error. Explanatory text is in .text(). In some cases it is a unhandled generic (500) app level Error.
* @param req The Express Request object from the request into TinyNode
* @param res The Express Response object to send out of TinyNode
* @param next The Express next() operator, unused here but required to support the middleware chain.
*/
export async function messenger(rerum_error_res, req, res, next) {
if (res.headersSent) {
return
}
const error = {
message: rerum_error_res.statusMessage ?? rerum_error_res.message ?? "A server error has occurred",
status: rerum_error_res.statusCode ?? rerum_error_res.status ?? 500,
}
if (rerum_error_res.payload !== undefined) {
console.error(error)
res.status(error.status).json(rerum_error_res.payload)
return
}
try {
const contentType = rerum_error_res.headers?.get?.("Content-Type")?.toLowerCase?.() ?? ""
if (contentType.includes("json")) {
error.body = await rerum_error_res.json()
console.error(error)
res.status(error.status).json(error.body)
return
}
const rerumErrText = await rerum_error_res.text()
if (rerumErrText) {
error.message = rerumErrText
}
}
catch (err) {
// Fall back to the status/message values already collected above.
}
console.error(error)
res.set("Content-Type", "text/plain; charset=utf-8")
res.status(error.status).send(error.message)
}