Home > Net >  How can I handle json-parse errors in node.js
How can I handle json-parse errors in node.js

Time:10-12

My problem seems to be fairly simple and common, but nevertheless I can't seem to find anything about it after hours of research:

I want to retrieve JSON-data in Node.js via http-POST using Express. To keep it simple, I want to use the app.use(express.json()); function (see code).

When the JSON-data is correct JSON-syntax, everything works fine, but when there is a syntax error in the JSON-data, it handles the error on its own, automatically replying to the client and logging a huge error message on the console. What I'd like to do is to handle the error the way I want, but I'm not sure how I can manage to do that.

The code I'm using is the following:

const express = require('express');

const app = express();

app.use(express.json());

app.post('/', function(req, res) {
    // do something with the retreived JSON-data
});

I would be very thankful if somebody could give me a tip/solution! :)

CodePudding user response:

You could handle malformed JSON errors using this, as the error is an instance of SyntaxError

app.use((error, request, response, next) => {
    if (error instanceof SyntaxError)
        response.status(404).send('your error message');
    else 
        next();
});
  • Related