Node Js - Valid JSON body before it reaches API router endpoint "SyntaxError: Unexpected string in JSON at position 83
   at JSON.parse"

When using node js with express, sometimes we get some unexpected errors from the API endpoint which doesn't really makes sense to the API consumer. On the other hand, we need to send appropriate message and Http Code to the consumer.

If you pass invalid Json body to a node Js API, you may get the following enexpected error.




"SyntaxError: Unexpected string in JSON at position 83<br> &nbsp; &nbsp;at JSON.parse"

We can clearly see, such errors can't be handled accurately by the consumer application as it has lot of HTML data as response.

To fix this, you can try to handle the parser error in the router endpoint and return apropriate message to the consumer, but there is an issue, the middleware itself returns the above error to the consumer, before it reaches the API end point.


So, the solution is pretty simple and will be applicable to all the APIs. Write a middleware to handle this error like following.

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//Custom JSON parsing error handling middleware
app.use((err, req, res, next) => {
  if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
    return res.status(400).json({ error: 'Invalid JSON body' });
  }
  next();
});

Now, this will handle all Json parsing error, and you get proper messages on error. This error handling middleware can be enxtended for various usages.





Thank you for reading!



Comments

Popular posts from this blog

SharePoint log error "Cannot find site lookup info for request Uri http://"

Visual Studio Build Issue : Build: 0 succeeded or up-to-date, 0 failed, 1 skipped

Reset your SharePoint Farm PassPhrase