Catch express bodyParser error

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

    I found checking for SyntaxError to be not enough, therefore I do:

    if (err instanceof SyntaxError &&
      err.status >= 400 && err.status < 500 &&
      err.message.indexOf('JSON') !== -1) {
        // process filtered exception here
    }
    

提交回复
热议问题