@@ -20,6 +20,19 @@ import bodyParser, { OptionsJson } from "body-parser";
20
20
import { NextFunction , Request , Response } from "express" ;
21
21
import { HTTPError } from "lambert-server" ;
22
22
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
+
23
36
export function BodyParser ( opts ?: OptionsJson ) {
24
37
const jsonParser = bodyParser . json ( opts ) ;
25
38
@@ -29,8 +42,15 @@ export function BodyParser(opts?: OptionsJson) {
29
42
30
43
jsonParser ( req , res , ( err ) => {
31
44
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 ) ) ;
34
54
}
35
55
next ( ) ;
36
56
} ) ;
0 commit comments