Repository navigation
Expand file tree
/
Copy patherror-handler.ts
More file actions
52 lines (45 loc) · 1.41 KB
/
Copy patherror-handler.ts
File metadata and controls
52 lines (45 loc) · 1.41 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
import type {
ErrorRequestHandler,
Request,
RequestHandler,
Response,
} from "express";
import { HttpErrors } from "../http/http.error.js";
import { logError } from "../http/log-error.js";
import { type AnyError, toProblem } from "../http/problem-details.js";
// Used by the routes for expected failures and by the handlers below.
export function sendProblem(
req: Request,
res: Response,
error: AnyError,
): void {
const problem = toProblem(error, { instance: req.path, requestId: req.id });
res.status(problem.status).type("application/problem+json").json(problem);
}
// Registered after the routes: no route matched.
export const notFoundHandler: RequestHandler = (req, res) =>
sendProblem(req, res, HttpErrors.routeNotFound(req.method, req.path));
// Registered last: everything a route or middleware throws ends up here.
export const errorHandler: ErrorRequestHandler = (
error: unknown,
req,
res,
next,
) => {
if (res.headersSent) {
return next(error);
}
if (isMalformedJson(error)) {
return sendProblem(req, res, HttpErrors.malformedJson());
}
logError(req.id, error);
return sendProblem(req, res, HttpErrors.unexpected());
};
// express.json() fails with a SyntaxError of this type when the body is not JSON.
function isMalformedJson(error: unknown): boolean {
return (
error instanceof SyntaxError &&
"type" in error &&
error.type === "entity.parse.failed"
);
}