使用循环 twitteR 查询处理 404 和其他不良响应 [英] Handling 404 and other bad responses with looping twitteR queries

查看:34
本文介绍了使用循环 twitteR 查询处理 404 和其他不良响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的循环在出现错误时不会中断,我会很高兴.我希望它继续进行下一次迭代.这个例子是我得到的错误和循环中断的最小例子.在我的实际应用程序中,我正在遍历我从另一个脚本生成的一些关注者.

图书馆(twitteR)#设置oauth...for(i 在 1:10) {+ x <- getUser("nalegezx") }

<块引用>

twInterfaceObj$doAPICall(paste("users", "show", sep = "/"), params = params, 中的错误:客户端错误:(404) 未找到

我知道这个循环只会重写对 x 的相同响应.我只是对不打破循环感兴趣.

解决方案

我不是 R Twitter API 的专家,但我可以建议您考虑调用 getUser()在像这样的 try 块中:

for (i in 1:10) {x <- try(getUser("sdlfkja"))}

这应该会阻止您的代码在循环中间崩溃.如果你想在循环中出现警告或错误时也有单独的逻辑,你可以使用 tryCatch:

for (i in 1:10) {x <- tryCatch(getUser("sdlfkja"),警告 = 函数(w){打印(警告");# 在这里处理警告},错误 = 函数(e){打印(错误");# 在这里处理错误})}

I would like it if my loop wouldn't break if I get an error. I want it to just move on to the next iteration. This example is a minimal example of the error I'm getting and the loop breaking. In my real application I'm iterating through some of the followers I've generated from another script.

library(twitteR)
#set oauth...
for(i in 1:10) {
+ x <- getUser("nalegezx") }

Error in twInterfaceObj$doAPICall(paste("users", "show", sep = "/"), params = params, : client error: (404) Not Found

I understand that this loop would simply rewrite the same response to x. I'm just interested in not breaking the loop.

解决方案

I'm not an expert in the R Twitter API, but I can suggest that you consider placing your call to getUser() inside a try block like this:

for (i in 1:10) {
    x <- try(getUser("sdlfkja"))
}

This should stop your code from crashing in the middle of the loop. If you want to also have separate logic when a warning or error occurs in the loop, you can use tryCatch:

for (i in 1:10) {
    x <- tryCatch(getUser("sdlfkja"),
                  warning = function(w) {
                                print("warning"); 
                                # handle warning here
                            },
                  error = function(e) {
                              print("error");
                              # handle error here
                          })
}

这篇关于使用循环 twitteR 查询处理 404 和其他不良响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆