我正在使用 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/