Skip to content
Advertisement

How to catch unhandledRejection?

I wrote a Telegram bot using TelegrafJS, this framework wraps the Telegram API. The problem that I’m facing is how to correctly manage the unhandled rejection, in fact when I call this method:

await ctx.deleteMessage(message_id);

where ctx is the instance of TelegrafJS I got:

Bot error: Error: 400: Bad Request: message to delete not found

this error happens ’cause the message_id that I passed no longer exists in Telegram chat. Now, the problem is that I have several controllers which can cause that problem.

I was looking at Promise.prototype.catch(), my question is: can I set up a global rejection handler for my application, or should I use a try/catch block to methods potentially subject to exceptions?

Advertisement

Answer

Yes you can, and it is pretty simple:

process.on('unhandledRejection', (err) => {
    //handle it!
});

You can also catch the unhandled exceptions, using the same code basically:

process.on('uncaughtException', (err) => {
    //handle it!
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement