Catch express bodyParser error

前端 未结 6 529
忘了有多久
忘了有多久 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:23
    (bodyParser, req, res) => new Promise((resolve, reject) => {
        try {
            bodyParser(req, res, err => {
                if (err instanceof Error) {
                    reject(err);
                } else {
                    resolve();
                }
            });
        } catch (e) {
            reject(e);
        }
    })
    

    Bullet-proof. Future-aware. WTFPL-Licensed. And also useful w/ async/await.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 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()
      }
    })
    
    0 讨论(0)
  • 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 ());
    
    0 讨论(0)
  • 2020-12-29 18:30

    I think your best bet is to check for SyntaxError:

    app.use(function (error, req, res, next) {
      if (error instanceof SyntaxError) {
        sendError(res, myCustomErrorMessage);
      } else {
        next();
      }
    });
    
    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
提交回复
热议问题