I am coding a discord.js bot and need a command where the first argument is a Message-ID.
Because a fetch() returns a promise, it's not guaranteed that the message will be found (obviously if the ID is wrong), so only if finds the message, it goes into the .then(), if not, I just make .catch(msg.delete())
BUT, I still get a warning in the console UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
But if I change the catch block to .catch(console.error) the warnings vanish and I get a object-kinda output. But I dont that this error will be displayed in my console, neither I want those warnings. My bot should just remove the message, because it's the users fault to type an invalid id.
And one question: when exactly does the catch block trigger, if the ID (args[0]) is per se valid (18 chars and only numbers) but still not matching to any message, or if its just anything causing an error in the Promise.
Thanks in advance!
Here is a bit more code:
msg.channel.messages.fetch(args[0])
.then(message => {
console.log("then");
})
.catch(console.log("catch"));
what's really interesting, if my ID is valid, then it says first "catch", and then "then". If its invalid it says "catch" and then comes the warning message
Try .catch((err) => { console.log(err); msg.delete(); });
Related
I am trying to implement a discord chatbot into my own bot, isn't good at handling some characters and stuff like the quotes of discord (type > and space to know that I mean). It often crashes becauses it thinks the message is empty. I wanted to use a try catch phrase so it won't crash. The complete function is asyncronous and I think that's why it isn't working how I want it to do. It still crashes without logging the thrown error.
client.on("message", async message => {
if(message.channel.id === "1006483461747527772" && !message.author.bot){
if(containsLetters(message.content)) {
//console.log(message.content.length)
try{
let reply = await chat.chat(message.content)
client.channels.cache.get("1006483461747527772").send(reply)
} catch(err){
client.channels.cache.get("1006483461747527772").send(err)
}
}
}
})
#Robotgozoooom's answer is correct that to send an error message to Discord you need to use error.message, but there's another problem: when Discord throws the Cannot send empty message error it is in an async function, so the try/catch doesn't actually catch the error. You need to add a .catch() function to the end of your async function instead of using a try/catch at all:
if (containsLetters(message.content)) {
let reply = await chat.chat(message.content);
let channel = client.channels.cache.get("1006483461747527772");
channel.send(reply).catch((err) => channel.send(err.message));
}
I think the problem that you are running into here is that the object err is not a String. Try appending .message to err so then it reads err.message. If that doesn't work (or even if it does), I would recommend against sending the error message in discord since that presents more variables to interfere with debugging (what if something was wrong with the client object or with the channel id string?). Instead, I normally use console.error(err). Hope this helps!
I have been trying to find a way to save a message as a variable. After it is saved as variable, I will delete the variable. I am making a page-based command for my bot, where each page has a custom reaction that does a custom action. I decided to make a simple navigator for the first page. In the navigator, you react with an emoji and the bot sends a message telling you to choose a page and wait for your message. When the bot receives your message, I want the bot to delete the message it sent.
My code looks like this.
let qsend = message.channel.send("Choose a page to go to.");// sends the bot's message
// bot receives my message!
qsend.delete() // deletes the bot's message
When I run it, I get the error: UnhandledPromiseRejectionWarning: TypeError: qsend.delete is not a function.
I've tried many different solutions, but still nothing.
Sending a message returns a promise. You need to either await it or use Promise#then()
Using Async/Await
// Inside an async function
// .on('message' async message => ... For example
let qsend = await message.channel.send("Choose a page to go to.");
qsend.delete();
Using Promise#then()
message.channel.send("Choose a page to go to.")
.then(qsend => qsend.delete())
.catch(console.error);
Discord.JS Documentation on Message#delete() and Async/Await
message.channel.send() returns a promise (see here). To delete it shortly after, you should send the message, await the response and delete the returned message after that time.
message.channel.send('Foo bar')
.then(msg => msg.delete())
.catch(/* Error handling if the message isn't sent or returned.*/);
I just graduated from a Full Stack Bootcamp and this is my first post. I am still trying to learn and apply all of this stuff. Working on a portfolio project for a server using NodeJs/MongoDB/Mongoose and am trying to figure out how to intercept the .catch error and generate my own error message. I'm making a PUT request using an object ID for a specific record and everything is working when a valid ID is passed. However, if I test using an invalid ID it goes straight to catch error and bypasses my handling of this type of scenario. Here is the code I'm trying to manipulate:
.put((req, res, next) => {
Guitar.findByIdAndUpdate(req.params.guitarId, {$set: req.body}, { new: true })
.then(guitar => {
if (guitar) {
console.log(guitar);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(guitar);
} else {
res.statusCode = 403;
res.setHeader('Content-Type', 'text/plain');
res.end(`${req.params.guitarId} does not match any guitars in database`);
}
})
.catch(err => next(err));
})
I assumed that if I tried to pass an invalid ID then if(guitar) would return false, then return my error code. But instead it appears that if an invalid ID is sent then it never gets to that point, instead giving the "Cast to Object Id" failure outside of my if/else code. Am I approaching this incorrectly? Thanks in advance for any insight!!!
The Cast to ObjectId failed is occurring before the find operation is sent to the server, so there is never a chance for the promise to resolve and move on to the .then.
You might try explicitly casting the value to ObjectId inside a try-catch block to handle that specific issue, or add some to the .catch for that error.
I know you can send a DM like this:
message.author.send("Go to example.com for help");
But some people have the setting that allows other server members to DM them off:
How do I find out if the DM actually sent or not? I know this is possible in the Discord API, since other bots do it.
If the user has that option, or isn't DMable, it will throw an error, namely:
DiscordAPIError: Cannot send messages to this user
Now, we can catch that error and run a command based on it, say replying in the channel that the user can't be DMed.
user.send(...).catch(async err => message.reply("I can't DM this user"));
// In the above, async is useless, but you can actually do what you want with it.
To run more than a single line of command, use a promise based catch.
user.send(...).catch(async err => {
console.log(err);
message.reply("I can't DM this user");
});
If a user has that option enabled, DMing them will return an error, so you'll be able to use a .catch() statement:
user.send().catch(() => console.log('Could not DM this user'));
You can get error notices aswell as information about the error using .catch()
In this example I log the error type and description
member.send(...).catch(error => {
console.error(`${error.name} :\n${error}`)
message.channel.send('There was an error when trying to DM this member')
})
I've managed to load data and to save data. But cannot understand the error handling scheme needed.
When everything goes fine I receive the same object in that was sent but with an extra attribute _saving (false).
When something goes wrong, for instance try to store a string instead of a number, I'll get:
Bad request (error on the console, don't want that)
The response object (might be usefull to show an error)
"Uncaught (in promise)" error
Example:
Code:
this.save()
.then(function(result) {
console.log('ok1', result);
}).catch(function() {
console.log('errorHandler1');
});
OK:
Error:
I've been trying to use catch on promises, following this guidelines:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
but had no luck at all.
This should should work buy just changing p1.then to thisObjectThatIWantToSave.save.then but it didn't.
p1.then(function(value) {
console.log(value); // "Success!"
throw 'oh, no!';
}).catch(function(e) {
console.log(e); // "oh, no!"
}).then(function(){
console.log('after a catch the chain is restored');
}, function () {
console.log('Not fired due to the catch');
});
Again, it still stores the information when the data is correct, the problem I see is that I don't have the tools to decide when was the data correctly stored or not and to avoid triggering errors that can be correctly handled.
I'm using
canjs v3.0.0-pre.11
a restful API provided by feathers
Regarding the error handling ...
Bad request (error on the console, don't want that)
There's no way of preventing the error on the console. This is something chrome does.
The response object (might be usefull to show an error)
You can read the reason for the rejection in can-stache like {{promise.reason}}.
"Uncaught (in promise)" error
I'm not sure why this is being thrown as clearly, your catch is being hit. If you change it to:
this.save()
.then(function(result) {
console.log('ok1', result);
},function() {
console.log('errorHandler1');
});
Do you get the same behavior?