Skip to content

Commit 2a033d8

Browse files
committed
feat: add try-catch encapsulation mode
1 parent f7e2c01 commit 2a033d8

File tree

3 files changed

+28
-3
lines changed

3 files changed

+28
-3
lines changed

R/encapsulate.R

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
#' * `"none"`: Just runs the call in the current session and measures the elapsed time.
88
#' Does not keep a log, output is printed directly to the console.
99
#' Works well together with [traceback()].
10+
#' * `"try-catch"`: Similar to `"none"`, but catches error. Output is printed to the console and
11+
#' not logged.
1012
#' * `"evaluate"`: Uses the package \CRANpkg{evaluate} to call the function, measure time and do the logging.
1113
#' * `"callr"`: Uses the package \CRANpkg{callr} to call the function, measure time and do the logging.
1214
#' This encapsulation spawns a separate R session in which the function is called.
@@ -54,19 +56,26 @@
5456
encapsulate = function(method, .f, .args = list(), .opts = list(), .pkgs = character(),
5557
.seed = NA_integer_, .timeout = Inf) {
5658

57-
assert_choice(method, c("none", "evaluate", "callr"))
59+
assert_choice(method, c("none", "try-catch", "evaluate", "callr"))
5860
assert_list(.args, names = "unique")
5961
assert_list(.opts, names = "unique")
6062
assert_character(.pkgs, any.missing = FALSE)
6163
assert_count(.seed, na.ok = TRUE)
6264
assert_number(.timeout, lower = 0)
6365
log = NULL
6466

65-
if (method == "none") {
67+
if (method %in% c("none", "try-catch")) {
6668
require_namespaces(.pkgs)
6769

6870
now = proc.time()[[3L]]
69-
result = invoke(.f, .args = .args, .opts = .opts, .seed = .seed, .timeout = .timeout)
71+
if (method == "none") {
72+
result = invoke(.f, .args = .args, .opts = .opts, .seed = .seed, .timeout = .timeout)
73+
} else {
74+
result = try(invoke(.f, .args = .args, .opts = .opts, .seed = .seed, .timeout = .timeout))
75+
if (inherits(result, "try-error")) {
76+
result = NULL
77+
}
78+
}
7079
elapsed = proc.time()[[3L]] - now
7180
} else if (method == "evaluate") {
7281
require_namespaces(c("evaluate", .pkgs))

man/encapsulate.Rd

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tests/testthat/test_encapsulate.R

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,17 @@ test_that("timeout", {
5454
expect_true("error" %in% res$log$class)
5555
expect_true(any(grepl("time limit", res$log$msg)))
5656
})
57+
58+
59+
test_that("try-catch", {
60+
fun1 = function(...) {
61+
message("foo")
62+
}
63+
64+
fun2 = function(...) {
65+
message("foo")
66+
}
67+
68+
expect_message(encapsulate("try-catch", function(...) message("foo")))
69+
expect_warning(encapsulate("try-catch", function(...) warning("foo")))
70+
})

0 commit comments

Comments
 (0)