Raynor
Raynor

Reputation: 277

R: Function returns both error and warning - store both with tryCatch()

I am using readLines() in [R] and for some URLs, it gives me errors, together with a warning message:

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

As you can see, the function returns both a generic error and a more specific explanation in the warning. Currently, I am using tryCatch() and some lines to print and store these errors using conditionMessage(). However, this only stores the generic uninformative eroror message while I'm actually more interested in the warning text. How can I store both?

Working example:

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)
})}

Desired outcome would be something like:

      [,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"

Upvotes: 1

Views: 187

Answers (1)

Karsten W.
Karsten W.

Reputation: 18490

You could turn the warning into in error, with

options(warn=2)

On the other hand, this would only return the warning (as error) in tryCatch.

Upvotes: 1

Related Questions