Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

220
Visualizações
Try - Catch not responding properly when JSON has a backslash

I have a router.post as follows

router.post('/newlead', async (payload, res, next) => {
...
...
...
});

Payload is coming on the body, as a JSON object, for example

{
    "name": "Danielle",
    "age": 26
}

When I send a body like this:

{
    "name": "\Danielle",
    "age": 26
}

I get the error

SyntaxError: Unexpected token in JSON at position X.

I tried by JSON.parse(payload.body) within a try{}catch{} and I still get the error, its like try/catch wouldn't be there.

This is happening with POSTMAN, but not with the Angular application.

Is there a way to identify this error and display a message to the user?

UPDATE: The code is too long to post, but this is what is not working:

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

router.post('/newlead', async (payload, res, next) => {
    try{
    let test=JSON.parse(payload.body)
    console.log("ok")
    }
    catch(err) {
    console.log(err)
    return;
    }
    res.json(payload.body)

});
module.exports = router;

This is my middleware at index.js

//Middleware
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', '*');
    res.header("Access-Control-Allow-Headers", "accept, content-type");
    next();
})
app.use(express.json()); //to read bodies
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Your express.json() middleware is encountering an error when parsing the invalid JSON sent by the client, and the framework is serving up a default error handling response.

To handle the error in a custom way, consider installing custom error handling middleware like this:

app.use(function (err, req, res, next) {
  if (err.type === 'entity.parse.failed') {
    // Your custom error handler here
    res.status(500).send('The client sent invalid JSON');
  } else {
    // Something else went wrong. Pass it along.
    next(err);
  }
})

Important: ensure this middleware is installed last, after all other app.use directives.

over 4 years ago · Santiago Trujillo Relatório

0

You need something like the body-parser middleware because express can't parse the not valid json. Thats why your try catch doesn't works

// ...
app.use(bodyParser.json());

// Handle a parse error
app.use((err, req, res, next) => {
    if (err) {
        res.send('error parsing data')
    } else {
        next()
    }
})
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda