javascript - 尝试...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
解决方案
对于简单的 try...catch,您已经x
在代码中声明了变量。没有 2 个变量可以被命名为相同的东西,所以它会给你一个语法错误。如果您想更改 的值x
,只需执行x = 2
.
对于您的代码,它无法在 fetch 方法中找到用户 ID。这可能是因为前缀长度不正确,或者您的 substr 方法没有获取方法内容的正确部分。无论哪种方式,您都应该尝试使用该子字符串声明一个变量,然后console.log
对该变量进行 ing。
推荐阅读
- python - 尝试逐步迭代python中的2个文件
- c - 为什么我可以修改这个 const char* 数组?
- java - 使用 PhotoView 放大后无法达到图像的原始大小
- java - 复制屏幕以在眼镜中使用。安卓
- java - OpenFeign 自定义错误解码器未捕获 ConnectionException
- python - 对 IO 绑定但独立的进程使用多处理或异步?
- laravel-mix - 如何在 Laravel Mix 上对 SASS/SCSS 进行 lint
- c++ - 在 ffmpeg 编码过程中更新参数正在运行
- node.js - 配置 Cypress 的 Electron 浏览器来处理下载
- java - .txt 文件一直显示“null”