I’m working on a bot to fetch a user’s avatar, I use try...catch
for user mention detection, but it still throws an error.
And I tried a simple try...catch
, and it throws an error SyntaxError: Identifier 'x' has already been declared
:
try { let x = 1; let x = 2; // Variable already been declared } catch (e) { console.log(e) }
Here’s my code:
// 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 atn${msg.content}n`); else embeds.commandInvalidParam.setDescription(````Invalid parameter atn${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 Using:
Virtual Studio Code
Version: 1.54.3 (user setup)
Commit: 2b9aebd5354a3629c3aba0a5f5df49f43d6689f8
Date: 2021-03-15T10:55:45.459Z
Electron: 11.3.0
Chrome: 87.0.4280.141
Node.js: 12.18.3
V8: 8.7.220.31-electron.0
OS: Windows_NT x64 10.0.18363
Advertisement
Answer
For the simple try…catch, you have already declared the x
variable in your code. No 2 variables can be named the same thing, so it’s going to give you a syntax error. If you want to change the value of x
, just do x = 2
.
For your code, it can’t find the user ID inside the fetch method. This could be because the prefix isn’t the right length, or your substr method isn’t getting the right parts of the method content. Either way, you should try declaring a variable with that substring, and then console.log
ing the variable.