2

我正在向 Facebook Graph API 请求用户详细信息,例如

require(RJSONIO)
response <- RJSONIO::fromJSON("http://graph.facebook.com/?ids=Jack")
print(response)
# $Jack
# id       first_name           gender        last_name           locale 
# "534213341"           "Jack"           "male"      "Lindamood"          "en_US" 
# name         username 
# "Jack Lindamood"   

都好。

但有时我有一个来自 API 的错误要处理。比如这个错误响应(希望没人会拿这个用户名...)

{
   "error": {
      "message": "(#803) Some of the aliases you requested do not exist: this.username.does.not.exist.because.i.made.it.up",
      "type": "OAuthException",
      "code": 803
   }
}

如果我尝试用 RJSONIO 解析它

RJSONIO::fromJSON("http://graph.facebook.com /?ids=this.username.does.not.exist.because.i.made.it.up")

我明白了

Error in file(con, "r") : cannot open the connection

但是,如果我首先解析 json,RCurl我会收到 rjson 格式的错误消息

require(RCurl)
json <- getURL("http://graph.facebook.com/?ids=this.username.does.not.exist.because.i.made.it.up")
RJSONIO::fromJSON(json)
$error
$error$message
[1] "(#803) Some of the aliases you requested do not exist: this.username.does.not.exist.because.i.made.it.up"

$error$type
[1] "OAuthException"

$error$code
[1] 803

可以使用 ? 直接管理错误RJSONIO

4

1 回答 1

4

你可以做

result <- try(RJSONIO::fromJSON("http://graph.facebook.com/?ids=this.username.does.not.exist.because.i.made.it.up"), 
              silent=TRUE)`

class(result)在处理前检查(try-error如果您收到您发布的错误)。

您还可以使用httr包(直接使用包的现代分支RSJSONIO- jsonlite)与RJSONIO包:

library(httr)

content(GET("http://graph.facebook.com/?ids=Jack"), as="parsed")
content(GET("http://graph.facebook.com/?ids=this.username.does.not.exist.because.i.made.it.up"),
        as="parsed")
## $error
## $error$message
## [1] "(#803) Some of the aliases you requested do not exist: this.username.does.not.exist.because.i.made.it.up"
## 
## $error$type
## [1] "OAuthException"
## 
## $error$code
## [1] 803
于 2015-02-01T02:38:55.350 回答