Skip to content

Commit 708f6d1

Browse files
committed
tryCatch failsafe
1 parent 161d3b7 commit 708f6d1

File tree

1 file changed

+56
-28
lines changed

1 file changed

+56
-28
lines changed

R/utils.R

Lines changed: 56 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -176,41 +176,69 @@ process_request <- function(
176176
} else {
177177
show_progress <- FALSE
178178
}
179-
for (i in seq_len(pages)) {
180-
api_response <- make_get_request(
181-
token = token,
182-
path = path,
183-
instance = instance,
184-
params = params,
185-
anonymous = anonymous
186-
)
187-
output <- c(output, api_response)
188-
attr(output, "headers") <- attr(api_response, "headers")
189-
if (
190-
break_process_request(
191-
api_response = api_response,
192-
retryonratelimit = retryonratelimit,
193-
verbose = verbose,
194-
pager = pager
195-
)
196-
) {
197-
break
198-
}
199-
params[[pager]] <- attr(api_response, "headers")[[pager]]
200-
if (verbose && show_progress) {
201-
utils::setTxtProgressBar(pb, i)
179+
180+
# Wrap the pagination loop in tryCatch to preserve partial results on error
181+
result <- tryCatch(
182+
{
183+
for (i in seq_len(pages)) {
184+
api_response <- make_get_request(
185+
token = token,
186+
path = path,
187+
instance = instance,
188+
params = params,
189+
anonymous = anonymous
190+
)
191+
output <- c(output, api_response)
192+
attr(output, "headers") <- attr(api_response, "headers")
193+
if (
194+
break_process_request(
195+
api_response = api_response,
196+
retryonratelimit = retryonratelimit,
197+
verbose = verbose,
198+
pager = pager
199+
)
200+
) {
201+
break
202+
}
203+
params[[pager]] <- attr(api_response, "headers")[[pager]]
204+
if (verbose && show_progress) {
205+
utils::setTxtProgressBar(pb, i)
206+
}
207+
}
208+
list(output = output, error = NULL)
209+
},
210+
error = function(e) {
211+
# On error, return what we have so far along with error information
212+
list(output = output, error = e)
202213
}
203-
}
214+
)
215+
204216
if (isTRUE(parse)) {
205-
header <- attr(output, "headers")
217+
header <- attr(result$output, "headers")
206218

207-
output <- FUN(output)
208-
attr(output, "headers") <- header
219+
result$output <- FUN(result$output)
220+
attr(result$output, "headers") <- header
209221
}
222+
223+
# Add error information as an attribute if an error occurred
224+
if (!is.null(result$error)) {
225+
attr(result$output, "rtoot_error") <- result$error
226+
attr(result$output, "partial_result") <- TRUE
227+
if (verbose) {
228+
cli::cli_warn(
229+
c(
230+
"Request interrupted by error. Returning partial results.",
231+
"i" = "Error message: {result$error$message}",
232+
"i" = "Retrieved {nrow(result$output)} items before error"
233+
)
234+
)
235+
}
236+
}
237+
210238
if (show_progress) {
211239
cat("\n")
212240
}
213-
return(output)
241+
return(result$output)
214242
}
215243

216244
## vectorize function

0 commit comments

Comments
 (0)