简体   繁体   中英

Why am I getting error "UnhandledPromiseRejectionWarning" when running my code?

I am trying to use the node.js discord module to make a bot that will send a private message to a user when a command is entered in discord. The command is supposed to be used like

!rp <@recipient>

and the message is delivered to the recipient.

My code is:

else if (rhysmessage.substring(0,4) == ("!rp ")) {
e.message.delete();
var end
var charactercheck
for (end=0; charactercheck < rhysmessage.length; charactercheck = 
charactercheck + 1) {
  console.log(rhysmessage.charAt(charactercheck))
  if (rhysmessage.charAt(charactercheck) == " ") {
    end = charactercheck}
}
if (end == 0){
  rhyschannel.sendMessage("Please use format `!rp <recipient> 
<message>`")
}
else {
  usersendto = rhysmessage.substring(5,end-1)   
usersendto.sendMessage(rhysmessage.substring(end+1,rhysmessage.leng
th)
    }
   }

When I run this code, I get the error: "UnhandledPromiseRejectionWarning". Why is this?

See here for information about unhandled promise rejections.

Explanation:
Some methods (ie send() within Discord.js ) return promises . Quoted from MDN...

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

In other words, some functions have to wait for something to be completed. When there's an error, the promise is rejected, and you must handle it. The warning you see is due to the fact that your code isn't catching any rejected promises.

Solution:
Implement the use of .catch() methods or try...catch statements to handle any errors.

await channel.send('hey')
.catch(err => console.error(err));
try {
  await channel.send('hey');
  await user.send('hey again');
} catch(err) {
  console.error(err);
}

Please note that although in the example above the error will be sent to the console, it won't stop your code. Make sure to handle it correctly so that any further code doesn't run into errors. Also, to use await , you must be within async functions.

// sendMessage() is deprecated in Discord.js. Use send() instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM