Repository navigation
Expand file tree
/
Copy patherror-handler.ts
More file actions
60 lines (53 loc) · 1.7 KB
/
Copy patherror-handler.ts
File metadata and controls
60 lines (53 loc) · 1.7 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
import { errorCodes, type FastifyReply, type FastifyRequest } from "fastify";
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(
request: FastifyRequest,
reply: FastifyReply,
error: AnyError,
): FastifyReply {
const problem = toProblem(error, {
instance: pathOf(request),
requestId: request.id,
});
return reply
.code(problem.status)
.type("application/problem+json")
.send(problem);
}
// Passed to setNotFoundHandler: no route matched.
export function notFoundHandler(
request: FastifyRequest,
reply: FastifyReply,
): FastifyReply {
return sendProblem(
request,
reply,
HttpErrors.routeNotFound(request.method, pathOf(request)),
);
}
// Passed to setErrorHandler: everything a route or hook throws ends up here.
export function errorHandler(
error: unknown,
request: FastifyRequest,
reply: FastifyReply,
): FastifyReply {
if (isMalformedJson(error)) {
return sendProblem(request, reply, HttpErrors.malformedJson());
}
logError(request.id, error);
return sendProblem(request, reply, HttpErrors.unexpected());
}
// Fastify's JSON parser fails with one of these when the body is not JSON.
function isMalformedJson(error: unknown): boolean {
return (
error instanceof errorCodes.FST_ERR_CTP_INVALID_JSON_BODY ||
error instanceof errorCodes.FST_ERR_CTP_EMPTY_JSON_BODY
);
}
// request.url keeps the query string; Express's req.path does not.
function pathOf(request: FastifyRequest): string {
return request.url.split("?")[0];
}