errors with Javascript try catch

errors with Javascript try catch

本文关键字:catch try Javascript with errors      更新时间:2023-09-26

我用Javascript编写了一个项目,并使用try/catch,如下所示:

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);
    }

启动程序后,显示此错误:

/var/www/html/marketer_bot/classes/Products.js:54抛出"其他";

例如:Products.js:54表示throw "other";

我不知道出了什么问题!你能帮我吗?

您正在抛出一个异步执行的回调。这意味着代码块将在try-catch语句运行完毕后执行。

当回调执行时,您需要处理回调中的错误:

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
  }
});