Skip to contents

This function validates an object using a list of checks. If any check fails, an error handler is called and a default value is returned. This function is intended to slightly simplify cases where a long list of complex and convoluted predetermined checks are needed. For simpler cases like type checking, it is recommended to use stopifnot() or assertthat::assert_that().

Usage

validateObject(obj, checks, errorHandler = warningp, defaultReturn = NULL)

Arguments

obj

The object to validate.

checks

A single function or list of functions, each taking the object as an argument and returning NULL if the check passes or an error message if the check fails.

errorHandler

A function to handle errors, taking the error message as an argument. Default is warning.

defaultReturn

The value to return if any check fails. Default is NULL.

Value

The original object if all checks pass, or defaultReturn if any check fails.

Examples

# Define some checks
checkNotNull <- function(x) if (is.null(x)) "Object is NULL" else NULL
checkIsNumeric <- function(x) {
    if (!is.numeric(x)) "Object is not numeric" else NULL
}

# Validate an object
obj <- 42
validateObject(obj, list(checkNotNull, checkIsNumeric))
#> [1] 42

# Validate an object that fails a check
obj <- NULL
try(
    validateObject(
        obj,
        list(checkNotNull, checkIsNumeric, errorHandler = stop)
    ),
    silent = TRUE
)
#> Warning: Object is NULL
#> NULL