Skip to content

Commit 1473af0

Browse files
committed
catch errors when constructor needs arguments
1 parent d131575 commit 1473af0

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

R/layer.R

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,16 @@ validate_subclass <- function(x, subclass,
471471
name <- snakeize(name)
472472
obj <- find_global(name, env = env, mode = "function")
473473
if (is.function(obj)) {
474-
obj <- obj()
474+
obj <- try_fetch(
475+
obj(),
476+
error = function(cnd) {
477+
# replace `obj()` call with name of actual constructor
478+
cnd$call <- call(name)
479+
cli::cli_abort(
480+
"Failed to retrieve a {.cls {subclass}} object from {.fn {name}}.",
481+
parent = cnd, call = call
482+
)
483+
})
475484
}
476485
# Position constructors return classes directly
477486
if (inherits(obj, subclass)) {

tests/testthat/_snaps/layer.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@
2727

2828
`environment()` must be either a string or a <geom> object, not an environment.
2929

30+
---
31+
32+
Failed to retrieve a <Geom> object from `geom_foo()`.
33+
Caused by error in `geom_foo()`:
34+
! This function is unconstructable.
35+
3036
# unknown params create warning
3137

3238
Ignoring unknown parameters: `blah`

tests/testthat/test-layer.R

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ test_that("layer() checks its input", {
1010

1111
expect_snapshot_error(validate_subclass("test", "geom"))
1212
expect_snapshot_error(validate_subclass(environment(), "geom"))
13+
14+
geom_foo <- function(...) stop("This function is unconstructable.")
15+
expect_snapshot_error(layer("foo", "identity", position = "identity"))
1316
})
1417

1518
test_that("aesthetics go in aes_params", {

0 commit comments

Comments
 (0)