zerobias / telegram-mtproto

Telegram client api (MTProto) library
MIT License
617 stars 136 forks source link

Try/catch doesn't work #224

Closed Niek closed 5 years ago

Niek commented 5 years ago

Running the latest master - the try/catch approach as shown in for example https://github.com/zerobias/telegram-mtproto/blob/master/examples/login.js doesn't work. What is the correct way to handle exceptions? Both try/catch as well as .catch() chaining doesn't work.

karianpour commented 5 years ago

I guess that some where in the code it is forgotten to run reject function. That's why we get unhandled rejection. I get it when I encounter NETWORK_BAD_REQUEST, and the flow of the program is broken.

karianpour commented 5 years ago

So I wrote a workaround for it, it is not a solution, but it is better than hanging code. Instead of the following code:

async function aFunc () {
...
  try{
    let history = await telegram('messages.getHistory', params);//if you get an error, it swallows it
  } catch (err) {
    // if it does not fulfill in 5 seconds, it comes here
  }
...
}

write it this way:

async function aFunc () {
...
  try{
    let history = await runWithTimeout(telegram, 'messages.getHistory', params);
  } catch (err) {
    // if it does not fulfill in 5 seconds, it comes here
  }
...
}
async function runWithTimeout(telegram, method, params){
  return new Promise(function(resolve, reject) {
    telegram(method, params).then(result => resolve(result))
    .catch(err => reject(err));
      setTimeout(function() {
        reject(new Error('timed out'));
    }, 5000);
  });
}
Niek commented 5 years ago

A better long term solution will be to use TDweb, see https://github.com/tdlib/td/issues/127#issuecomment-479123702 and the WASM binaries in https://github.com/evgeny-nadymov/telegram-react/tree/master/public - I'm closing this issue.