Skip to content

Commit 08fc90a

Browse files
Merge pull request #1189 from greysilly7/dev/bodyparser
2 parents 346641c + e67b28a commit 08fc90a

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

src/api/middlewares/BodyParser.ts

+22-2
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,19 @@ import bodyParser, { OptionsJson } from "body-parser";
2020
import { NextFunction, Request, Response } from "express";
2121
import { HTTPError } from "lambert-server";
2222

23+
const errorMessages: { [key: string]: [string, number] } = {
24+
"entity.too.large": ["Request body too large", 413],
25+
"entity.parse.failed": ["Invalid JSON body", 400],
26+
"entity.verify.failed": ["Entity verification failed", 403],
27+
"request.aborted": ["Request aborted", 400],
28+
"request.size.invalid": ["Request size did not match content length", 400],
29+
"stream.encoding.set": ["Stream encoding should not be set", 500],
30+
"stream.not.readable": ["Stream is not readable", 500],
31+
"parameters.too.many": ["Too many parameters", 413],
32+
"charset.unsupported": ["Unsupported charset", 415],
33+
"encoding.unsupported": ["Unsupported content encoding", 415],
34+
};
35+
2336
export function BodyParser(opts?: OptionsJson) {
2437
const jsonParser = bodyParser.json(opts);
2538

@@ -29,8 +42,15 @@ export function BodyParser(opts?: OptionsJson) {
2942

3043
jsonParser(req, res, (err) => {
3144
if (err) {
32-
// TODO: different errors for body parser (request size limit, wrong body type, invalid body, ...)
33-
return next(new HTTPError("Invalid Body", 400));
45+
const [message, status] = errorMessages[err.type] || [
46+
"Invalid Body",
47+
400,
48+
];
49+
const errorMessage =
50+
message.includes("charset") || message.includes("encoding")
51+
? `${message} "${err.charset || err.encoding}"`
52+
: message;
53+
return next(new HTTPError(errorMessage, status));
3454
}
3555
next();
3656
});

0 commit comments

Comments
 (0)