Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
How can I handle json-parse errors in node.js

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! :)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!