Catch express bodyParser error

前端 未结 6 521
忘了有多久
忘了有多久 2020-12-29 17:55

I want to catch the error from the bodyParser() middleware when I send a json object and it is invalid because I want to send a custom response instead of a generic 400 erro

6条回答
  •  一整个雨季
    2020-12-29 18:29

    Ok, found it:

    bodyParser() is a convenience function for json(), urlencoded() and multipart(). I just need to call to json(), catch the error and call to urlencoded() and multipart().

    bodyParser source

    app.use (express.json ());
    app.use (function (error, req, res, next){
        //Catch json error
        sendError (res, myCustomErrorMessage);
    });
    
    app.use (express.urlencoded ());
    app.use (express.multipart ());
    

提交回复
热议问题