Skip to content

Instantly share code, notes, and snippets.

@kvasilopoulos
Created April 23, 2020 17:15
Show Gist options
  • Save kvasilopoulos/47f24348ed75cdb6365312b17f4b914c to your computer and use it in GitHub Desktop.
Save kvasilopoulos/47f24348ed75cdb6365312b17f4b914c to your computer and use it in GitHub Desktop.
Packages which use Internet resources should fail gracefully
CRAN policy:
''Packages which use Internet resources should fail gracefully with an
informative message if the resource is not available (and not give a
check warning nor error).'
library(httr)
library(curl)
gracefully_fail <- function(remote_file) {
try_GET <- function(x, ...) {
tryCatch(
GET(url = x, timeout(1), ...),
error = function(e) conditionMessage(e),
warning = function(w) conditionMessage(w)
)
}
is_response <- function(x) {
class(x) == "response"
}
# First check internet connection
if (!curl::has_internet()) {
message("No internet connection.")
return(invisible(NULL))
}
# Then try for timeout problems
resp <- try_GET(remote_file)
if (!is_response(resp)) {
message(resp)
return(invisible(NULL))
}
# Then stop if status > 400
if (httr::http_error(resp)) {
message_for_status(resp)
return(invisible(NULL))
}
# If you are using rvest as I do you can easily read_html in the response
xml2::read_html(resp)
}
gracefully_fail("http://httpbin.org/status/404") # http >400
#> Not Found (HTTP 404).
gracefully_fail("http://httpbin.org/delay/2") # Timeout
#> Timeout was reached: [httpbin.org] Operation timed out after 1000 milliseconds with 0 bytes received
gracefully_fail("http://httpbin.org") #OK
#> {html_document}
#> <html lang="en">
#> [1] <head>\n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8 ...
#> [2] <body>\n <a href="https://github.com/requests/httpbin" class="github-c ...
skip_if_http_error <- function() {
remote_file <- "https://www.nationwide.co.uk/about/house-price-index/download-data"
skip_if(httr::http_error(remote_file))
}
skip_if_offline()
skip_if_http_error()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment