Convenience function for validating that an object is not NULL.

stopIfNull(target, msg = NULL)

Arguments

target

Object to test.

msg

Optional error message to display if target is NULL. Must be a character string of length one.

Value

Invisibly returns target when it is not NULL.

Details

If target is not NULL, it is returned invisibly. If target is NULL, the function stops with either a default or user-supplied error message.

This function is especially useful for validating required function arguments or for guarding intermediate results in pipelines.

Examples

# Return input invisibly if not NULL
x <- stopIfNull(5)
print(x)
#> [1] 5

# Useful in pipelines
y <- 1:10
y_mean <-
  y %>%
  stopIfNull() %>%
  mean()

if (FALSE) { # \dontrun{
# Trigger the default error message
testVar <- NULL
stopIfNull(testVar)

# Trigger a custom error message
stopIfNull(testVar, msg = "This is NULL")

# Make a failing pipeline
z <- NULL
z_mean <-
  z %>%
  stopIfNull("This has failed.") %>%
  mean()
} # }