我正在尝试构造一个循环函数,该函数从 R 中的 API 捕获 json,如下所示:
for(j in 1:700){
tx_i <- paste0("https://example.com/api/",bloco_i_final$tx[j])
txi <- GET(tx_i, add_headers(Authorization = full_token, Accept =
header_type), timeout(120), verbose())
conteudo <- content(txi, type = 'text', encoding = "UTF-8")
tx_i_final <- rjson::fromJSON(getURL(tx_i))
(some functions that bind this data.frames)
}
但有时,在循环中,此函数最终会出现一条错误消息:
Error in fromJSON(conteudo) : unexpected character 'B'
我想构建一个 while 函数来识别此错误并重复该过程。
示例:
for(j in 1:700){
#THIS PART
while(identifies erro in FROMJSON){
tx_i <- paste0("https://example.com/api/tx/",bloco_i_final$tx[j])
txi <- GET(tx_i, add_headers(Authorization = full_token, Accept =
header_type), timeout(120), verbose())
conteudo <- content(txi, type = 'text', encoding = "UTF-8")
tx_i_final <- rjson::fromJSON(getURL(tx_i))
} #REPEATS ALL PROCESS WHILE ERRO EXISTS
(some functions that bind this data.frames)
}
您可以使用
的一个技巧是在循环中实现 tryCatch(.)
方法,然后减少计数器。例如:
for(j in 1:100){
tryCatch({
#Define the link with all positions
### Implement your method here!! ###
}, error = function(err) {
#Print the error:
print(paste("MY_ERROR: ",err))
#Decrease your counter to try again
j<- (j-1)
#Wait some time before try again...
Sys.sleep(10)
})
}