首页 > 解决方案 > Twitter Bot 错误 - 未处理的承诺拒绝?

问题描述

我写了这个 twitter 天气机器人,从上个月开始运行良好,但一个小时前它崩溃了,我似乎无法恢复它。

谁能简单地解释一下它是什么以及错误是什么,何时出现以及我必须检查什么才能消除此警告?

我确实搜索了如何解决“未处理的承诺拒绝”,但找不到它是什么。

const Twit = require('twit');
const config = require('./config');
const rp = require('request-promise-native');

async function setup(location) {
    const options = {
        url: "http://api.apixu.com/v1/current.json",
        qs: { 
            key: API_KEY,
            q: location
        },
        json: true
    };
    let result = await rp(options);
    let condition = result.current.condition.text;
    let tweetText = `The condition in ${location} is currently ${condition}, and the temperature is ${result.current.temp_c}°C.`;
    console.log(tweetText);
    sendTweet(tweetText)
}

function sendTweet(text) {
    const T = new Twit(config);
    var r = Math.floor(Math.random()*1000);
    const tweet = {
        status: '[' + r + '] ' + text
    }

    T.post('statuses/update', tweet);
}
setup('Colombo');

2019-08-21T06:41:52.820595+00:00 app[scheduler.8141]: at setup (/app/bot.js:25:36)

2019-08-21T06:41:52.820597+00:00 app[scheduler.8141]: at process._tickCallback (internal/process/next_tick.js:68:7)

2019-08-21T06:41:52.820719+00:00 app[scheduler.8141]: (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

2019-08-21T06:41:52.820834+00:00 app[scheduler.8141]: (node:4) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

2019-08-21T06:41:52.903455+00:00 heroku[scheduler.8141]: State changed from up to complete

2019-08-21T06:41:52.880762+00:00 heroku[scheduler.8141]: Process exited with status 0```

标签: javascriptnode.jspromise

解决方案


当您使用以下方式调用 api 时:

let result = await rp(options);

您将结果设置为等待 API 调用的承诺,但由于某种原因您的请求未被接受,然后您收到承诺拒绝但未处理。

请用:

await rp(options).catch(err => console.log(err))

因此,您可以记录您的错误,然后我们可以调查您的错误。

- - - - - 编辑 - - - - - -

刚刚自己测试了一下,我们得到了一个 503 HTTP 状态码:

这是日志打印

这意味着该服务不可用,没有收到请求。

- - - - - 编辑 - - - - - -

它再次工作,在这里尝试,我得到 200 HTTP 状态代码和良好的响应,现在你应该很高兴


推荐阅读