0

I'm requesting some data from an API - in particular https://api.tvmaze.com/singlesearch/shows?q=Friends&embed=episodes usually, when I get an invalid request with APIs I get it in JSON format. So I can easily send that data back (to discord). But with this API if you replace friends with a random string it returns a page saying This api.tvmaze.com page can't be found. How can I send this data back to the user?

I'm using NodeJS and the node-fetch module to get the request.

fetch('https://api.tvmaze.com/singlesearch/shows?q=' + msg + '&embed=episodes') //msg is the users input
  .then(function(res) {
    return res.json();
  }).then(function(json) {
    console.log(json.network.name) // if input is friends this returns NBC
  });
  • 1
    I am not familiar with the exact library you are using, but before checking the body of the response, you could check the status. The page not found is 404, and in that case you can create an object to return to discord your self. – Ken Apr 21 '17 at 22:59
  • Ken is right. Put another way, have a check for if parse json fails. If it does fail, implement whatever behavior you want to have in case of failure. – Goose Apr 21 '17 at 23:02
  • @Ken How would I check it though? If it was a JSON response I would usually do `(if json.error === 404)` for example, but this of course isn't in JSON, how do I check the status? –  Apr 21 '17 at 23:03
  • Can you edit your question to include your code that makes the call to the API? I can help you better if I can see how you are handling it. – Ken Apr 21 '17 at 23:08

1 Answers1

0

So I am not 100% familiar with node-fetch but I think you can check the status of the res in your .then() function.

fetch('https://api.tvmaze.com/singlesearch/shows?q=' + msg + '&embed=episodes') //msg is the users input
  .then(function(res) {
    if(res.status === 404) {
        //HANDLE THE 404 Page Not Found
    } else {
        return res.json();
    }
  }).then(function(json) {
    console.log(json.network.name) // if input is friends this returns NBC
  });
Ken
  • 466
  • 2
  • 7