-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy patherror-messenger.js
More file actions
34 lines (34 loc) · 1.66 KB
/
error-messenger.js
File metadata and controls
34 lines (34 loc) · 1.66 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
/**
* 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 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
}
let error = {}
let rerum_err_text
try {
// Unless already handled upstream the rerum_error_res is an error Response with details as a textual body.
rerum_err_text = await rerum_error_res.text()
}
catch (err) {
// It is some 500
rerum_err_text = undefined
}
if (rerum_err_text) error.message = rerum_err_text
else {
// Perhaps this is a more generic 500 from the app, perhaps involving RERUM, and there is no good rerum_error_res
error.message = rerum_error_res.statusMessage ?? rerum_error_res.message ?? `A server error has occured`
}
error.status = rerum_error_res.statusCode ?? rerum_error_res.status ?? 500
console.error(error)
res.set("Content-Type", "text/plain; charset=utf-8")
res.status(error.status).send(error.message)
}