2

When parsing expected JSON input, I use a try catch statement to determine whether or not the response body is indeed JSON, and store this in a variable:

let noParseErr = true;
try {
  JSON.parse(body);
} catch (err) {
  console.error(err);
  noParseErr = false;
} finally {
  if (noParseErr) {
    // do stuff
  }
}

Is there a better approach to this?

Almatrass
  • 125
  • 7
  • JSON.Parse throws an `Error` upon failure, this is the only way of doing this. – Hudson Aug 09 '18 at 13:26
  • You are not changing the variable `noParseErr`, so, yes, a better approach would be changing it's value to `false` when an error occurs – Luca Kiebel Aug 09 '18 at 13:27
  • why are you define a variable with true once and then just check it with an if? I'm talking about noParseErr – Philipp Sander Aug 09 '18 at 13:28
  • you have try and catch blocks... you dont need an "noParseErr" variable at all – Philipp Sander Aug 09 '18 at 13:28
  • Sorry I changed the code now, forgot to change the variable on catch err – Almatrass Aug 09 '18 at 13:30
  • I personally detest using try/catch to determine whether or not something is valid, but sometimes it just is the only reasonable option. I'd just create a function though, like `function isValidJson(json)` and have try return true and catch return false. It's just a bit tidier than checking it where you use it, and reusable for _**when**_ you want to do the same thing later. – Reinstate Monica Cellio Aug 09 '18 at 13:33

0 Answers0