Skip to content

Instantly share code, notes, and snippets.

@wbreeze
Created October 14, 2019 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wbreeze/86e187cf0800783df9ca1e5b997ddc74 to your computer and use it in GitHub Desktop.
Save wbreeze/86e187cf0800783df9ca1e5b997ddc74 to your computer and use it in GitHub Desktop.
Using tryCatch() from R together with reduce() from Purrr
> source("tryWithError.R")
List of 7
$ :List of 4
..$ value : num 1
..$ success: logi TRUE
..$ errors : NULL
..$ data : int 1
$ :List of 4
..$ value : num 3
..$ success: logi TRUE
..$ errors : NULL
..$ data : int [1:3] 1 2 3
$ :List of 4
..$ value : num 5
..$ success: logi TRUE
..$ errors : NULL
..$ data : int [1:5] 1 2 3 4 5
$ :List of 4
..$ value : num 7
..$ success: logi TRUE
..$ errors : NULL
..$ data : int [1:7] 1 2 3 4 5 6 7
$ :List of 4
..$ value : num 9
..$ success: logi TRUE
..$ errors : NULL
..$ data : int [1:9] 1 2 3 4 5 6 7 8 9
$ :List of 4
..$ value : num 15
..$ success: logi FALSE
..$ errors : chr "Failed toTry(15), error: 15 is greater than twelve"
..$ data : list()
$ :List of 4
..$ value : num 21
..$ success: logi FALSE
..$ errors : chr "Failed toTry(21), error: 21 is greater than twelve"
..$ data : list()
List of 2
$ data : int [1:25] 1 1 2 3 1 2 3 4 5 1 ...
$ errors: chr [1:4] "There was trouble with value 15" "Failed toTry(15), error: 15 is greater than twelve" "There was trouble with value 21" "Failed toTry(21), error: 21 is greater than twelve"
>
require(purrr)
toTry <- function(value) {
if (12 < value) {
stop(sprintf("%d is greater than twelve", value))
}
seq(1, value)
}
tryWithError <- function(value) {
errors <- c()
success <- TRUE
onError <- function(e) {
errors <<- c(errors, sprintf("Failed toTry(%d), error: %s",
value, e$message))
success <<- FALSE
list()
}
data <- tryCatch(toTry(value), error=onError, warning=onError)
list(value=value, success=success, errors=errors, data=data)
}
reduction <- function(trackingList, value) {
result = tryWithError(value)
if (result$success) {
trackingList$data <- if (is.null(trackingList$data)) {
result$data
} else {
c(trackingList$data, result$data)
}
} else {
trackingList$errors <- c(
trackingList$errors,
sprintf("There was trouble with value %d", value),
result$errors
)
}
trackingList
}
values <- c(1, 3, 5, 7, 9, 15, 21)
testTryWithL <- function() {
str(lapply(values, tryWithError))
}
testTryWithReduce <- function() {
str(reduce(values, reduction, .init=list()))
}
testTryWithL()
testTryWithReduce()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment