Catch express bodyParser error

前端 未结 6 566
忘了有多久
忘了有多久 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:32

    From the answer of @alexander but with an example of usage

    app.use((req, res, next) => {
        bodyParser.json({
            verify: addRawBody,
        })(req, res, (err) => {
            if (err) {
                console.log(err);
                res.sendStatus(400);
                return;
            }
            next();
        });
    });
    
    function addRawBody(req, res, buf, encoding) {
        req.rawBody = buf.toString();
    }
    

提交回复
热议问题