Catch express bodyParser error

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

    what I did was just:

    app.use(bodyParser.json({ limit: '10mb' }))
    // body parser error catcher
    app.use((err, req, res, next) => {
      if (err) {
        res.status(400).send('error parsing data')
      } else {
        next()
      }
    })
    

提交回复
热议问题