Error when accessing API with discord.js, but only on an embed?

Viewed 158

I am making a Discord bot which gets data from the Hypixel API, an API for a Minecraft server. I have managed to write some code which successfully gets the data, but this is where I am running into an issue. When I directly message.channel.send the data, it works. However, if I use the data in an embed, it doesn't work.

Does work:

fetch(`https://api.hypixel.net/player?key=API_KEY&name=${args[1]}`)
      .then(result => result.json())
      .then(({ player }) => {

      message.channel.send(player.stats.Bedwars.coins)
})

Does not work:

fetch(`https://api.hypixel.net/player?key=API_KEY&name=${args[1]}`)
      .then(result => result.json())
      .then(({ player }) => {

      var bedwars_general_1 = new Discord.MessageEmbed()
      .addFields(
          { name: 'Coins', value: player.stats.Bedwars.coins, inline: true},
      )
      
      message.channel.send(bedwars_general_1)
})

With the top example, it works perfectly, however with the bottom one, I get this error message every single time:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'Bedwars' of undefined

It also gives me this error when I added this line var bedwarsCoins = player.stats.Bedwars.coins, before the embed and then added the variable to the embed field.

I cannot understand why it only works some of the time?

1 Answers

The error means that the stats property of player is undefined or null.

It's possible that the API couldn't find anything, which in that case you should try catching the absence of a value of the stats property.

.then(player => {
  if (!player.stats) return console.log('Unable to find stats');
});
Related