在Rfacebook中使用tryCatch或其他处理来调用callAPI错误

时间:2014-08-21 21:16:20

标签: r facebook error-handling try-catch

我有一个可能包含错误的facebook用户名列表。我想在很多方面调用getUsers并获得每个人有多少喜欢。如果getUsers遇到错误的用户名,我想从列表中删除它并再试一次。

我想在Rfacebook中这样做(但如果答案是我必须使用httr并自己编写GET请求,那就这样吧。)

load("fbCred.RData") # you will need a Facebook credential to execute this

library(Rfacebook)

fb_users <- c("brucespringsteen","coldplay")
fb_likes <- tryCatch(getUsers(users=fb_users,token=fbCred)$likes)
fb_likes # Returns: [1]  4807200 36768913

fb_users <- c("brucespringsteen","coldplay","This-Bad-Name-Will-Fail")
fb_likes <- tryCatch(getUsers(users=fb_users,token=fbCred)$likes)
# Returns:
# Error in callAPI(query, token) : 
#   (#803) Some of the aliases you requested do not exist: This-Bad-Name-Will-Fail
if(inherits(fb_likes,"error")){
  # I want to remove the one that failed from the list of users and try again. 
  # But the callAPI error never makes it into fb_likes. 
}

有没有办法在Rfacebook中做到这一点?如何检索坏用户的名称,以便我可以从列表中删除它并重试?

编辑:我知道我可以逐个遍历用户名。这是我目前的解决方法(使用adply)但需要更长的时间。

2 个答案:

答案 0 :(得分:1)

错误属于&#34;尝试错误&#34;,而不是&#34;错误&#34;。此外,您需要使用try,而不是tryCatch

fb_likes <- try(getUsers(users=fb_users,token=fbCred)$likes)
if(inherits(fb_likes, "try-error")) { ... }

应该有效。 tryCatch更复杂,需要不同的结构,例如:

tryCatch(
  fb_likes <- getUsers(users=fb_users,token=fbCred)$likes,
  error=function(e) { 
    err.msg <- conditionMessage(e)
    ...
} )

答案 1 :(得分:0)

load("fbCred.RData") # you will need a Facebook credential to execute this

library(Rfacebook)

fb_users <- c("brucespringsteen","coldplay","This_Will_Fail","Bad_Bad_Bad")

fb_likes <- try(getUsers(users=fb_users,token=fbCred)$likes)

if(inherits(fb_likes,"try-error")){
  bad_users <- unlist(strsplit(sub(".*exist\\:\\s+(.*)\\n$","\\1",
                           fb_likes[1]),split=","))
  print(paste("These user names failed, removing:", 
          paste(bad_users,collapse=", ")))
  fb_users <- setdiff(fb_users,bad_users)
  fb_likes <- getUsers(users=fb_users,token=fbCred)$likes
}
print(data.frame(fb_users,fb_likes))

产生所需的输出:

[1] "These user names failed, removing: This_Will_Fail, Bad_Bad_Bad"

          fb_users fb_likes
1 brucespringsteen  4808496
2         coldplay 36786558

要提取不良用户列表(使用正则表达式和strsplit),可以从geterrmessage()开始(假设它是最后一个错误),但从“{1}”开始可能更可靠try-error对象本身。然后我使用setdiff删除不良用户。