0

I am trying to handle Unexpetced JSON in my express js application via try and catch, so what I am trying to do is

try{
  let body = JSON.parse(req.body);
}catch(e){
   res.json({
    error:e
  })
}

But the Unexpected JSON error not thrown in the catch block.

Content-type is application/json

Here is the JSON request

{
    "userId":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InNoYW1vbjVAYWNjdWJpdHMuY29tIiwiaWQiOjExNCwiaWF0IjoxNTMxOTgyNDQ0LCJleHAiOjE1MzI1ODcyNDR9.dv1zEnLsmKXbSE4wKbSOdYX3p7v5N5nh9kbz6PA_4TE",
    "readValue":falseuyuyuyu
}

readValue is malformed

shamon shamsudeen
  • 5,466
  • 17
  • 64
  • 129

1 Answers1

0

you are missing " in the value of 'readValue'. it should be as follow :

{
"userId":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InNoYW1vbjVAYWNjdWJpdHMuY29tIiwiaWQiOjExNCwiaWF0IjoxNTMxOTgyNDQ0LCJleHAiOjE1MzI1ODcyNDR9.dv1zEnLsmKXbSE4wKbSOdYX3p7v5N5nh9kbz6PA_4TE",
"readValue":"falseuyuyuyu"
}

Edit: sorry didnt understand the question

Express has its own error handling middleware. in case of error, Express catches the error (in sync code) and handles it, That's why you cant get the error message. What you need to do is to write your own middleware that handles errors in your format. Please go to : https://expressjs.com/en/guide/error-handling.html and check Writing error handlers section.

dima golovin
  • 262
  • 2
  • 8