【问题标题】:Check if no data returned node-fetch discord.js检查是否没有数据返回 node-fetch discord.js
【发布时间】:2021-11-04 12:17:53
【问题描述】:

所以我正在尝试为我的机器人创建一个命令,将 Minecraft 用户名转换为uuid,当用户名无法识别时,mojang API 返回 NO 数据,有没有办法检查没有我的机器人崩溃了?

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})
        }

【问题讨论】:

    标签: javascript node.js discord.js node-fetch


    【解决方案1】:

    您可以使用Promise.prototype.catch() 捕获错误并添加if/else 条件,如下所示:

    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)
    });
    

    【讨论】:

    • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
    • 已更新,也将 cmets 作为代码执行的指南
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 2021-04-06
    • 2012-01-05
    • 1970-01-01
    相关资源
    最近更新 更多