Search code examples
javascriptnode.jsdiscord.jsnode-fetch

Check if no data returned node-fetch discord.js


So I'm trying to make a command for my bot that converts Minecraft usernames into uuid, the mojang API returns NO data when the username is not recognized, is there a way to check if no data was returned without my bot crashing?

fetch(`https://api.mojang.com/users/profiles/minecraft/${username}?`)
    .then(Result => Result.json())
    .then(async mojang => {
        if (mojang.empty) {
            return interaction.reply({content:`No user by the name of **${username}** was found`, ephemeral: true})
        }

Solution

  • You can catch error using Promise.prototype.catch() and adding if/else conditions like so:

    fetch(`https://api.mojang.com/users/profiles/minecraft/${username}?`).then((response) => {
      // check if initial response is okay
      if (response && response.ok) {
        return response.json();
      } else {
        // handle the error if no initial response was sent
      }
    })
    .then((responseJson) => {
      // If you get the final json response, proceed
    })
    .catch((error) => {
     // catch any type of errors related to the promise and handle it
      console.log(error)
    });