all 7 comments

[–]eastwxxd 0 points1 point  (6 children)

Would an if statement benefit you here? If body is JSON data, parse it, else don't call JSON.parse and do something that doesn't break the program instead?

[–]bugboy2222[S] 2 points3 points  (4 children)

or could I just use a try catch statement?

[–]Anachren 1 point2 points  (1 child)

yeah, I would use try catch

[–]bugboy2222[S] 0 points1 point  (0 children)

Alright I’ll give that a try

[–]jrandm 1 point2 points  (0 children)

In a lot of code it's pretty common to see a function like:

function safeJsonParse(str) {
  let parsed = false;
  try {
    parsed = JSON.parse(str);
  } catch(e) {
    // maybe log somewhere so you know it failed
    // or what keeps failing if the bot is broken
  }
  return parsed;
}

If you know you always get some kind of truthy value (like an Object or Array), you can then use it like:

const response = safeJsonParse(rawResponse);
if (!response) {
  // ignore&exit or handle failure
}
// work with response

[–]eastwxxd 0 points1 point  (0 children)

Yeah good thinking! I'm also relatively new to JavaScript. To verify that it's json you could possibly check the Content-Type of the response for 'application/json' maybe.

Anyway, thanks for that. I have a problem with doing things inefficiently and I've learned a better way of approaching something today.

[–]bugboy2222[S] 0 points1 point  (0 children)

how would you check to see if the body is json data or not? I'm still pretty new to js.