B. Azizan B. Azizan - 6 months ago 11
Javascript Question

errors with Javascript try catch

I wrote a project with Javascript and use try/catch as follows :

try{
var params = {
't_id': msg.from.username,
0: config.botToken
};
request.post({
url: urls.get('favorites'),
json:true,
body: {
jsonrpc: '2.0',
method: 'favorites',
params: params,
id: 1
}
}, function(error, response, body) {
if(body.result == undefined)
throw "other";

});
}catch(err)
{
let message = messages.getMessages(err);
console.log(message);
}


After starting the program, this error displayed :


/var/www/html/marketer_bot/classes/Products.js:54
throw "other";


Ex:
Products.js:54
refers to
throw "other";


I dont know what's the problem! can you help me?

Answer

You're throwing in a callback that is executed asynchronously. That means that block of code will be executed after your try-catch statement has already finished running.

You need to handle the errors in your callback while that callback is executing:

request.post({
  url: urls.get('favorites'),
  json:true,
  body: {
    jsonrpc: '2.0',
    method: 'favorites',
    params: params,
    id: 1
  }
}, function(error, response, body) {
  if(body.result == undefined) {
    // handle error right here
  }
});
Comments