Skip to content

Commit

Permalink
Add call argument to throw()
Browse files Browse the repository at this point in the history
  • Loading branch information
lionel- committed Apr 13, 2023
1 parent a5928a4 commit f7e7be7
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
7 changes: 5 additions & 2 deletions R/standalone-errors.R
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,10 @@ err <- local({
#' @param frame The throwing context. Can be used to hide frames from
#' the backtrace.

throw <- throw_error <- function(cond, parent = NULL, frame = environment()) {
throw <- throw_error <- function(cond,
parent = NULL,
call = parent.frame(),
frame = environment()) {
if (!inherits(cond, "condition")) {
cond <- new_error(cond)
}
Expand All @@ -240,7 +243,7 @@ err <- local({
}

if (isTRUE(cond[["call"]])) {
cond[["call"]] <- sys.call(-1) %||% sys.call()
cond[["call"]] <- frame_call(call)
} else if (identical(cond[["call"]], FALSE)) {
cond[["call"]] <- NULL
} else if (is.environment(cond[["call"]])) {
Expand Down
17 changes: 16 additions & 1 deletion tests/testthat/_snaps/standalone-errors.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,19 @@
# can pass frame as error call
# can pass frame as error call in `new_error()`

Code
(expect_error(f()))
Output
<rlib_error_3_0/rlib_error/error>
Error in `f()`:
! my message
Code
(expect_error(g()))
Output
<rlib_error_3_0/rlib_error/error>
Error in `g()`:
! my message

# can pass frame as error call in `throw()`

Code
(expect_error(f()))
Expand Down
18 changes: 17 additions & 1 deletion tests/testthat/test-standalone-errors.R
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ test_that("trace is printed on error in non-interactive sessions", {
expect_true(any(grepl("Backtrace", selines)))
})

test_that("can pass frame as error call", {
test_that("can pass frame as error call in `new_error()`", {
check_bar <- function(call = parent.frame()) {
check_foo(call = call)
}
Expand All @@ -366,3 +366,19 @@ test_that("can pass frame as error call", {
(expect_error(g()))
})
})

test_that("can pass frame as error call in `throw()`", {
check_bar <- function(call = parent.frame()) {
check_foo(call = call)
}
check_foo <- function(call = parent.frame()) {
throw(new_error("my message"), call = call)
}
f <- function() check_bar()
g <- function() check_foo()

expect_snapshot({
(expect_error(f()))
(expect_error(g()))
})
})

0 comments on commit f7e7be7

Please sign in to comment.