Home > Net >  Catch 500 error in nodejs when non-json returned
Catch 500 error in nodejs when non-json returned

Time:07-07

My function is process a jar file and return json. However, sometimes it return error (non-json) with 200 status code . this is annoying as I'm not able to catch the error from other applications. Could you please guide me how can i throw 500 error when the result is not json

 app.get("/MyPage", async (req, res) => {
       var data;
     
     
        try {
            do something...
        } catch (error) {
        // Error handle in end point with http error code (500)with some detail 
        }
    
        
    })

CodePudding user response:

try {
  var testIfJson = JSON.parse(data);
  if (typeof testIfJson == "object") {
    //Json
  }
  else {
    throw new Error();
  }
}

catch (error) {
  res.status(500).send("Internal Server Error");
}
  • Related