skip to Main Content

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?

2

Answers


  1. 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!
    });
    
    Login or Signup to reply.
  2. test this code:

    bot.use((ctx, next) => {
       try {
           ...
       } catch(error) {
           next();
       }
    })
    

    For error handler, you can use:

     bot.catch((err, ctx) => {
              console.log(err);
              return ctx.reply("Error Message");
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search