Home » Javascript » javascript – Error with promise rejections while using bulkDelete

javascript – Error with promise rejections while using bulkDelete

Posted by: admin February 26, 2020 Leave a comment

Questions:

So upon using the .bulkDelete() method, which deletes messages from a channel, I get this error:

UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message

(node:11720) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was
not handled with .catch(). (rejection id: 2) (node:11720) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In
the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.

Here is my code:

//delete the given amount of message + 1 for the sent message
let msgToDelete = parseInt(args[1]) + 1;

//filter messages too old and delete unfiltered messages
msg.channel.bulkDelete(msgToDelete, true)
  .then(deleted => {
    if (deleted.size <= 1) return;
    msg.channel.send(`deleted ${args[1]} messages.`)
      .then(m => m.delete(2500))
      .catch(err => console.error);
  }).catch(err => msg.channel.send(err));

Thanks in advance.

How to&Answers:

The problem is your catch has code which is throwing the exception which is not handled as it is occuring inside the catch block.

It is worth putting a catch at the global level and catch the error and log it.

Also, regarding the way you are chaining your promises, you could simplify that like this

//delete the given amount of message + 1 for the sent message
let msgToDelete = parseInt(args[1]) + 1;

//filter messages too old and delete unfiltered messages
msg.channel.bulkDelete(msgToDelete, true)
  .then(deleted => {
    if (deleted.size <= 1) return;
    return msg.channel.send(`deleted ${args[1]} messages.`);
  })
  .then(m => m.delete(2500))
  .catch(err => msg.channel.send(err));