Skip to contents

If any of the expressions in ... are not all TRUE, rlang::abort is called for the first expression which was not (all) TRUE. The associated error message will either be (in hierachy): from the name of the expression, the message argument, or the expression itself.

Usage

abort_if_not(..., .message = NULL, .class = NULL, .error_call = caller_env())

Arguments

...

any number of R expressions, which should each evaluate to (a logical vector of all) TRUE for no error to occur. If the expressions are named, the names will be used in the error message.

.message

single default error message for non-named expressions.

.class

class to assign to the error (passed to rlang::abort).

.error_call

the call environment to use for the error (passed to rlang::abort).

Details

abort_if() is the opposite of abort_if_not(), i.e. expressions should evaluate to (all) FALSE for no error to occur.

Examples

# NB: Some of these examples are expected to produce an error. To
#     prevent them from terminating a run with example() they are
#     piped into a call to try().

abort_if_not(1 == 1, all.equal(pi, 3.14159265), 1 < 2) # all TRUE

m <- matrix(c(1, 3, 3, 1), 2, 2)
abort_if_not(m == t(m), diag(m) == rep(1, 2)) # all TRUE

abort_if_not(length(10)) |> try()
#> Error in eval(expr, envir) : Error in `abort_if_not()`
#>  Expression `length(10)` must evaluate to class <logical> not <integer>.
# => Error: Expression `length(10)` for object `.data` must evaluate to
# class <logical> not <integer>.
# even when if(1) "ok" works

# The default error message can be overridden to be more informative:
m[1, 2] <- 12
abort_if_not("m must be symmetric" = m == t(m)) |> try()
#> Error in eval(expr, envir) : Error in `abort_if_not()`
#> m must be symmetric
# => Error: m must be symmetric

# Alternatively, one error message can be used for all expressions:
abort_if_not(
  m == t(m),
  diag(m) == rep(1, 2),
  message = "m must be symmetric and have 1s on the diagonal."
) |> try()
#> Error in eval(expr, envir) : Error in `abort_if_not()`
#>  Argument `m == t(m)` returned `FALSE`.
# => Error: m must be symmetric and have 1s on the diagonal.

abort_if(1 == 1) |> try() # abort_if errors if any argument does not evaluate to (all) FALSE
#> Error in eval(expr, envir) : Error in `abort_if()`
#>  Argument `1 == 1` returned `TRUE`.

# injection and glue can be used to supply expressions, names, and messages:
x <- "my error"
abort_if_not("{x}" = FALSE) |> try()
#> Error in eval(expr, envir) : Error in `abort_if_not()`
#> my error
# => Error: my error
y <- FALSE
abort_if_not({{ x }} := !!y) |> try()
#> Error in eval(expr, envir) : Error in `abort_if_not()`
#> my error
# => Error: my error
abort_if_not(!!x := !!y) |> try()
#> Error in eval(expr, envir) : Error in `abort_if_not()`
#> my error
# => Error: my error
x <- list("my error" = FALSE)
abort_if_not(!!!x) |> try()
#> Error in eval(expr, envir) : Error in `abort_if_not()`
#> my error
# => Error: my error