【问题标题】:How to use .catch() correctly? Unable to use it in certain code如何正确使用 .catch()?无法在某些代码中使用它
【发布时间】:2020-06-06 09:54:12
【问题描述】:

当我运行我的计划代码来发布消息时,每次发送消息时我都会收到以下错误消息:

未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。 (拒绝编号:3)

下面的代码一开始没有使用try {,但即使这样我也得到了同样的错误信息..

'use strict';

const Telegram = require('telegram-node-bot');
var schedule = require('node-schedule');

class AutoMsgController extends Telegram.TelegramBaseController {
    AutoMsgHandler(scope) {
        console.log(scope);
        if (statement) {
            const button = {'inline_keyboard': [
                [{ text: 'BUTTON1', url: 'URL1' }],
                [{ text: 'BUTTON2', url: 'URL2' }]
            ]}
            const parsedbutton = JSON.stringify(button);
            console.log(parsedbutton);
            scope.api.sendMessage(scope.message._chat._id, '*ACTIVATED!*', { 'parse_mode' : 'Markdown'});
            var j = schedule.scheduleJob('*/5 * * * * *', function(){ //5 Seconds
            scope.api.sendMessage(scope.message._chat._id, 'My message'
            ).then (
            function (e) {
                console.log ('Could not send automsg', e);
                throw e;
              }
            );
    }).catch((err) => {
        console.log('Api call error:', err.message)
      });
    }
}
    get routes() {
        return {
            'AutoMsgCommand': 'AutoMsgHandler'
        };
    }
}

module.exports = AutoMsgController;

如果我尝试使用 try { 我无法完成,它会说:finally expected

'use strict';

const Telegram = require('telegram-node-bot');
var schedule = require('node-schedule');

class AutoMsgController extends Telegram.TelegramBaseController {
    AutoMsgHandler(scope) {
        console.log(scope);
        if (statement) {
            try {
            const button = {'inline_keyboard': [
                [{ text: 'BUTTON1', url: 'URL1' }],
                [{ text: 'BUTTON2', url: 'URL2' }]
            ]}
            const parsedbutton = JSON.stringify(button);
            console.log(parsedbutton);
            scope.api.sendMessage(scope.message._chat._id, '*ACTIVATED!*', { 'parse_mode' : 'Markdown'});
            var j = schedule.scheduleJob('*/5 * * * * *', function(){ //5 Seconds
            scope.api.sendMessage(scope.message._chat._id, 'My message'
            ).then (
            function (e) {
                console.log ('Could not send automsg', e);
                throw e;
              }
            );
    }).catch((err) => {
        console.log('Api call error:', err.message)
      });
    }
  } //<- here is the problem `finally expected`
}
    get routes() {
        return {
            'AutoMsgCommand': 'AutoMsgHandler'
        };
    }
}

module.exports = AutoMsgController;

无法弄清楚...从其他帖子中我无法找到答案。

即使在这种情况下,它也会丢弃同样的东西......

'use strict';

const Telegram = require('telegram-node-bot');
var schedule = require('node-schedule');

class AutoMsgController extends Telegram.TelegramBaseController {
    AutoMsgHandler(scope) {
        console.log(scope);
        if (statement) {
            try {
            const button = {'inline_keyboard': [
                [{ text: 'BUTTON1', url: 'URL1' }],
                [{ text: 'BUTTON2', url: 'URL2' }]
            ]}
            const parsedbutton = JSON.stringify(button);
            console.log(parsedbutton);
            scope.api.sendMessage(scope.message._chat._id, '*ACTIVATED!*', { 'parse_mode' : 'Markdown'});
            var j = schedule.scheduleJob('*/5 * * * * *', function(){ //5 Seconds
            scope.api.sendMessage(scope.message._chat._id, 'My message'
            ).then (
            function (e) {
                console.log ('Could not send automsg', e);
                throw e;
              }
            );
    }).catch((err) => {
        console.log('Api call error:', err.message)
      });
        catch (error) {
        console.log('Api call error:', error)
      }
    }
}
    get routes() {
        return {
            'AutoMsgCommand': 'AutoMsgHandler'
        };
    }
}

module.exports = AutoMsgController;
'use strict';

const Telegram = require('telegram-node-bot');
var schedule = require('node-schedule');

class AutoMsgController extends Telegram.TelegramBaseController {
    AutoMsgHandler(scope) {
        console.log(scope);
        if (statement) {
            try {
            const button = {'inline_keyboard': [
                [{ text: 'BUTTON1', url: 'URL1' }],
                [{ text: 'BUTTON2', url: 'URL2' }]
            ]}
            const parsedbutton = JSON.stringify(button);
            console.log(parsedbutton);
            scope.api.sendMessage(scope.message._chat._id, '*ACTIVATED!*', { 'parse_mode' : 'Markdown'});
            var j = schedule.scheduleJob('*/5 * * * * *', function(){ //5 Seconds
            scope.api.sendPhoto(scope.message._chat._id, 'My Message'
            ).then (
                function (e) {
                    console.log ('Could not send automsg', e);
                    throw e;
                  }
                );
        }).catch((err) => {
            console.log('Api call error:', err.message)
          });         
        } catch (error) {
        console.log('Api call error:', error)
      }
    }
}
    get routes() {
        return {
            'AutoMsgCommand': 'AutoMsgHandler'
        };
    }
}

module.exports = AutoMsgController;

使用此代码取得进展 Api 调用错误:TypeError: schedule.scheduleJob(...).catch is not a function

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。 (拒绝编号:5)

【问题讨论】:

    标签: javascript node.js try-catch


    【解决方案1】:

    您忘记在尝试后放置catchfinally 块,以及使用then 而不是catch 进行错误处理。

    欲了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

    此外,您应该查看抛出的错误是什么,因为错误表明事务失败。

    'use strict';
    
    const Telegram = require('telegram-node-bot');
    var schedule = require('node-schedule');
    
    class AutoMsgController extends Telegram.TelegramBaseController {
        AutoMsgHandler(scope) {
            console.log(scope);
            if (statement) {
                try {
                const button = {'inline_keyboard': [
                    [{ text: 'BUTTON1', url: 'URL1' }],
                    [{ text: 'BUTTON2', url: 'URL2' }]
                ]}
                const parsedbutton = JSON.stringify(button);
                console.log(parsedbutton);
                scope.api.sendMessage(scope.message._chat._id, '*ACTIVATED!*', { 'parse_mode' : 'Markdown'});
                var j = schedule.scheduleJob('*/5 * * * * *', function(){ //5 Seconds
                scope.api.sendMessage(scope.message._chat._id, 'My message'
                ).then(function (response) {
                    // Do something with the response
                }).catch (
                function (e) {
                    console.log ('Could not send automsg', e);
                    throw e; // This still throws the same warning, but could be useful
                  }
                );
        }).catch((err) => {
            console.log('Api call error:', err.message)
          });
        }
      } catch (error) {
        // Do error handling stuff
      }
    }
        get routes() {
            return {
                'AutoMsgCommand': 'AutoMsgHandler'
            };
        }
    }
    
    module.exports = AutoMsgController;
    

    【讨论】:

    • “尝试”预期。
    • 不幸的是,现在它说 finallytry 是预期的..
    • ``` catch (error) { console.log('Api call error:', error) } } } ``` 代码本身没有问题......但在启动计划后我得到了同样的事情 UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。 (拒绝 ID:13)
    • 刚刚意识到您使用了then 方法,该方法在第 27 行的错误处理成功时执行,已修复。
    • 尝试了你的新答案,try' expected.also with 'finally' expected.
    【解决方案2】:

    这个呢:

    const Telegram = require("telegram-node-bot");
    var schedule = require("node-schedule");
    
    class AutoMsgController extends Telegram.TelegramBaseController {
      AutoMsgHandler(scope) {
        console.log(scope);
        if (statement) {
          try {
            const button = {
              inline_keyboard: [
                [{ text: "BUTTON1", url: "URL1" }],
                [{ text: "BUTTON2", url: "URL2" }],
              ],
            };
            const parsedbutton = JSON.stringify(button);
            console.log(parsedbutton);
            scope.api.sendMessage(scope.message._chat._id, "*ACTIVATED!*", {
              parse_mode: "Markdown",
            });
            var j = schedule
              .scheduleJob("*/5 * * * * *", function () {
                //5 Seconds
                scope.api
                  .sendMessage(scope.message._chat._id, "My message")
                  .then(function (e) {
                    console.log("Could not send automsg", e);
                    throw e;
                  }).catch((error) => {
                    console.log("sendMessage call error:", error.message);
                    throw error;
                  });;
              });
          } catch (error) {
            console.log("Api call error:", error);
          }
        }
      }
      get routes() {
        return {
          AutoMsgCommand: "AutoMsgHandler",
        };
      }
    }
    
    module.exports = AutoMsgController;
    

    【讨论】:

    • 我取得了进展,这也有效 :-) 错误是:Api call error: TypeError: schedule.scheduleJob(...).catch is not a function UnhandledPromiseRejectionWarning: Unhandled promise拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。 (拒绝编号:5)
    • 也许 "schedule.scheduleJob" 没有'返回承诺,尝试使用 var j = schedule .scheduleJob("*/5 * * * * *", function () { //5 秒范围。 api .sendMessage(scope.message._chat._id, "我的消息") .then(function (e) { console.log("Could not send automsg", e); throw e; }).catch((error) => { console.log("sendMessage call error:", error.message); throw error; }); }) 我的意思是没有catch
    • 也许问题是声明了j 的值,但它的值从未被读取。我没有找到如何让j 被读取以正确捕获错误的方法。这可能就是我一直有这个 .catch 警告的原因..
    猜你喜欢
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多