java - 为什么此代码会在 sleep 时导致 NPE 以避免 Twitter4J 中的速率限制?

标签 java twitter twitter4j rate-limiting

我正在使用 Twitter4j 来获取给定用户的关注者。在某些时候我总是达到速率限制。我很高兴程序 hibernate 15 分钟来克服这个问题。然而,当它醒来时,我收到一个错误。

请参阅以下代码:

protected IDs fetchAndStoreFollowers(TwitterUser user) {
    Twitter twitter = this.getTwitterApi();
    long cursor = -1;
    IDs ids = null;
    do {
        try {
            ids = twitter.getFollowersIDs(user.getId(), cursor);
            System.out.println("Got a followers batch");
            cursor = ids.getNextCursor();
            this.storeFollowers(user, ids);
            System.out.println("Saved!");
        } catch (TwitterException e) {
            System.out.println("Oh no! Rate limit exceeded... going to sleep.");
            handleTwitterException(e);
            System.out.println("Waking up!");
        }
    } while (ids.hasNext());
    return ids;
}

从 sleep 中唤醒后,程序在此行抛出 NullPointerException:

} while (ids.hasNext());

有人能看出原因吗?

最佳答案

遇到的错误的原因是可重现的并且非常合乎逻辑。

首先,将 ids 初始化为 null

如果发生 RateLimitException (TwitterException),则不会为以下行中的变量 ids 设置实际值:

ids = twitter.getFollowersIDs(user.getId(), cursor);

然后执行catch block 中的代码 - 而ids仍然指向null。处理完毕后(您会在控制台上看到输出...),该行:

while (ids.hasNext());

产生NullPointerException

解决方案

按如下方式更改 while 条件:

while (ids == null || (id!=null && ids.hasNext()));

请注意,如果出现错误情况,cursor 中的值可能尚未或必须相应更改。

希望这有帮助。

关于java - 为什么此代码会在 sleep 时导致 NPE 以避免 Twitter4J 中的速率限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42179999/

相关文章:

java - IntelliJ Maven Selenium 构建 jar

javascript - 如何在带有 node.js 的 express.js 上使用 twitter api 显示最后 20 条推文?

python - 我如何使用 Twitter 的流 api 中的推文并将它们存储在 mongodb 中

html - Twitter 卡片预览无法获取我的图像

java - 我如何获取已转发并扩展 140 个字符的推文的所有文本?

android - 如何使用 Twitter4j api 回复推文?

Twitter 集成 :consumer key/secret pair already set

java - Jenkins Junit 中的 WireMock - BindException : Address already in use

java - 从字符串中添加单个数字

java - startActivity 使应用程序强制关闭