R:函数返回错误和警告 - 使用tryCatch()存储

时间:2015-11-23 07:41:42

标签: r url error-handling try-catch

我在readLines()中使用[R],对于某些网址,它会给我发错,并附有警告信息:

Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") : cannot open: HTTP status was '401 Unauthorized'

如您所见,该函数在警告中返回一般错误和更具体的解释。目前,我正在使用tryCatch()和一些行来使用conditionMessage()打印和存储这些错误。但是,这只存储了通用的无信息eroror消息,而我实际上对警告文本更感兴趣。我怎么能同时存储?

工作示例:

errorlist <- NULL

for(i in 1:10){
tryCatch({
readLines("http://www.googl1.com/") # this URL does not exist
}, error = function(e){yy
  print(conditionMessage(e))
  assign("errorlist", c(errorlist, conditionMessage(e)), envir = .GlobalEnv)
})}

期望的结果将是:

      [,1]                     [,2]                                              
 [1,] "cannot open connection" "The server name or address could not be resolved"
 [2,] "cannot open connection" "The server name or address could not be resolved"
 [3,] "cannot open connection" "The server name or address could not be resolved"
 [4,] "cannot open connection" "The server name or address could not be resolved"
 [5,] "cannot open connection" "The server name or address could not be resolved"
 [6,] "cannot open connection" "The server name or address could not be resolved"
 [7,] "cannot open connection" "The server name or address could not be resolved"
 [8,] "cannot open connection" "The server name or address could not be resolved"
 [9,] "cannot open connection" "The server name or address could not be resolved"
[10,] "cannot open connection" "The server name or address could not be resolved"

1 个答案:

答案 0 :(得分:1)

您可以使用

将警告变为错误
options(warn=2)

另一方面,这只会在tryCatch中返回警告(作为错误)。