首页 > 解决方案 > 尝试...catch 在 JavaScript (Discord.js) 中不起作用

问题描述

我正在开发一个机器人来获取用户的头像,try...catch用于用户提及检测,但它仍然会引发错误。

我尝试了一个简单try...catch的,它抛出了一个错误SyntaxError: Identifier 'x' has already been declared

try {
    let x = 1;
    let x = 2; // Variable already been declared
} catch (e) {
    console.log(e)
}

这是我的代码:

// Get avatar by mention
try {
    client.users.fetch(msg.content.substr(prefix.length + 6, msg.content.length - prefix.length - 7)).then(result => {
        embeds.avatar
            .setTitle(`The avatar of ${msg.author.tag}`)
            .setImage(result.avatarURL({ dynamic: true }));
        msg.channel.send(embeds.avatar);
    });
} catch (e) {
    // Invalid user id
    logConsole('commandInvalidParam', msg);
    if (msg.content.length <= prefix.length + 14)
        embeds.commandInvalidParam.setDescription(`\`\`\`Invalid parameter at\n${msg.content}\n`);
    else
        embeds.commandInvalidParam.setDescription(`\`\`\`Invalid parameter at\n${msg.content.substr(0, prefix.length + 14)} ...\n`);
    for (let index = -4; index < prefix.length; index++)
        embeds.commandInvalidParam.setDescription(embeds.commandInvalidParam.description + ' ');
    embeds.commandInvalidParam.setDescription(embeds.commandInvalidParam.description + `^\`\`\`Type '${prefix}' for help`);
    msg.channel.send(embeds.commandInvalidParam);
}

IDE 使用:

虚拟工作室代码

版本:1.54.3(用户设置)

提交:2b9aebd5354a3629c3aba0a5f5df49f43d6689f8

日期:2021-03-15T10:55:45.459Z

电子:11.3.0

铬:87.0.4280.141

Node.js:12.18.3

V8:8.7.220.31-电子.0

操作系统:Windows_NT x64 10.0.18363

标签: javascriptdiscord.jstry-catch

解决方案


对于简单的 try...catch,您已经x在代码中声明了变量。没有 2 个变量可以被命名为相同的东西,所以它会给你一个语法错误。如果您想更改 的值x,只需执行x = 2.

对于您的代码,它无法在 fetch 方法中找到用户 ID。这可能是因为前缀长度不正确,或者您的 substr 方法没有获取方法内容的正确部分。无论哪种方式,您都应该尝试使用该子字符串声明一个变量,然后console.log对该变量进行 ing。


推荐阅读