Home > Software design >  How do I capture and use a JSON request I know will be incorrectly formatted?
How do I capture and use a JSON request I know will be incorrectly formatted?

Time:01-21

I'm trying to work up a proof of concept wherein I receive a POST request that then triggers a different POST request. I thought I would setup a nodejs/express server to test this, but the POST request I'm receiving has Content-Type application/json and a body with data that is (I believe) incorrectly formatted JSON.

e.g. { something: "data" }

I can't change this request, and I just need to use the data to send a different request, but Node throws an error: "Unexpected token in json at position" everytime it receives the request. I'm sure this is because the content is marked as JSON, but the body isn't formatted correctly; I just don't know enough about node/express to know how to deal with it. I looked at bodyParser and writing my own middleware function, but I could really use some direction.

Following DamiToma's advice I added error handling, but for some reason the middleware isn't being called:

const express = require('express');
const router = express.Router();

module.exports = router;

router.use((error, req, res, next) => {
    console.log("Error handling middleware called...");
    if(error instanceof SyntaxError) {
            switch(error.type) {
            case 'entity.parse.failed':
                // JSON is incorrect
                console.log('JSON is incorrect');
                break;
            default:
                // other error
                break;
        }

        res.status(400).end();
    } else {
        next();
    }
});

// POST
router.post('/post', (req, res) => {
    res.send('POST');
    console.log(req.body);

});

If I put the error handling on the app rather than router, it works, I'm just not sure why it doesn't apply when I put in on the router.

CodePudding user response:

Using express, you can setup a middleware to catch this kind of errors

router.use((error, req, res, next) => {
  if(error instanceof SyntaxError) {
    switch(error.type) {
      case 'entity.parse.failed':
        // JSON is incorrect
        break;
      default:
        // Some other kind of error happened
        break;
    }

    res.status(400).end();
  } else {
    next();
  }
})
  • Related