Make sure http fails are always handled gracefully
httr2: :req_error does not catch timeouts, and maybe more. So wrap req_perform in tryCatch to be on the safe side.
Change-Id: I913ea571e5fcbf2aa5adf1a455bfdfed487af05e
diff --git a/R/KorAPConnection.R b/R/KorAPConnection.R
index cd68a67..3627f2f 100644
--- a/R/KorAPConnection.R
+++ b/R/KorAPConnection.R
@@ -142,7 +142,11 @@
.Object@indexRevision <- .Object@welcome[[1]][["x-index-revision"]]
} else {
- message("Could not connect to KorAP instance ", .Object@KorAPUrl)
+ if (grepl(.Object@KorAPUrl, .Object@apiUrl)) {
+ message("Could not connect to KorAP instance ", .Object@KorAPUrl)
+ } else {
+ message("Could not connect to KorAP API at ", .Object@apiUrl)
+ }
}
.Object
})
@@ -359,6 +363,7 @@
# Create the request
req <- httr2::request(url) |>
httr2::req_user_agent(kco@userAgent) |>
+ httr2::req_error(is_error = \(resp) FALSE) |>
httr2::req_timeout(timeout)
if (! is.null(kco@oauthClient)) {
@@ -367,11 +372,14 @@
req <- req |> httr2::req_auth_bearer_token(kco@accessToken)
}
- resp <- req |>
- httr2::req_error(is_error = \(resp) FALSE) |>
- httr2::req_perform()
+ resp <- tryCatch(req |> httr2::req_perform(),
+ error = function(e) {
+ message(e$message, if("parent" %in% names(e)) paste0("\n", e$parent$message) else "")
+ return(NULL)
+ }
+ )
- # if (is.null(resp)) return(invisible(NULL))
+ if (is.null(resp)) return(invisible(NULL))
if (resp |> httr2::resp_status() != 200) {
message("Request failed with status ", resp |> httr2::resp_status(), ": ", resp |> httr2::resp_status_desc())
diff --git a/tests/testthat/test-KorAPConnection.R b/tests/testthat/test-KorAPConnection.R
index eea2265..b62aba2 100644
--- a/tests/testthat/test-KorAPConnection.R
+++ b/tests/testthat/test-KorAPConnection.R
@@ -3,11 +3,11 @@
})
test_that("KorAPConnection fails gracefully on timeout", {
- expect_message(new("KorAPConnection", apiUrl="http://httpbin.org/delay/3", timeout = 0.2), "No internet|Timeout|json|progress")
+ expect_message(new("KorAPConnection", apiUrl="http://httpbin.org/delay/3", accessToken = NULL, timeout = 0.2), "No internet|Timeout|json|progress")
})
test_that("KorAPConnection fails gracefully on Bad Gateway errors", {
- expect_message(new("KorAPConnection", apiUrl="http://httpbin.org/status/502", timeout = 0.5), "No internet|Timeout|progress|json|502")
+ expect_message(new("KorAPConnection", apiUrl="http://httpbin.org/status/502", accessToken = NULL, timeout = 0.5), "No internet|Timeout|progress|json|502")
})
test_that("KorAPConnection is printable", {