composerr
is an R package that helps building error handling functions which return meaningful error messages without doing copy/paste.
# Install development version from GitHub
devtools::install_github('R-package/composerr', build_opts = NULL)
The functions composerr
and composerr_parent
allow the concatenation of a more detailed error message to an already existing error handler (wich already has a rather basic information).
library(composerr)
#' The cool function `foo()`
#'
#' Function with error handling
#' @param x Must be a list object of length 3.
foo <- function(x) {
# create your general error handler
err <- composerr("While calling `foo`")
# modify the error handler to get a more detailed message
err_x <- composerr("Invalid argument `x`", err)
if (!is.list(x))
err_x("Not a list object.")
if (length(x) != 3)
err_x("Not of length 3.")
sum(unlist(x))
}
# call your function and
# get a meaningful error message
foo(list(1, 2, 3, 4))
## Error: While calling `foo`: Invalid argument `x`: Not of length 3.
The function composerr_parent
looks up the existing error handler in the parent environment and not in the current environment. This can be useful in nested scoping situations (for example when checking if a nested list object has a valid structure) and if you want to store the nested error handler functions under the same name (overriding error handler functions).
#' The cool function `foo()`
#'
#' Function with error handling
#' @param x Must be a list object of length 3
#' and all entries of `x` must be non-missing numbers.
foo <- function(x) {
# add the period at the end of the error message automatically
err <- composerr(
text_1 = "While calling `foo`",
text_2 = ".",
sep_2 = ""
)
err_x <- composerr("Invalid argument `x`", err)
if (!is.list(x))
err_x("Not a list object")
if (length(x) != 3)
err_x("Not of length 3")
sapply(seq_len(length(x)), function(i) {
val <- x[[i]]
# modify error handler inside of nested scope
# and store it under the same name (`err_x`)
err_x <- composerr_parent(
paste0("List entry `", i, "`"),
err_x
)
if (!is.numeric(val)) {
err_x("Not a number")
}
if (is.na(val))
err_x("Is `NA`")
})
sum(unlist(x))
}
# call your function and
# get a meaningful error message
foo(list(1, 2, NA))
## Error: While calling `foo`: Invalid argument `x`: List entry `3`: Not a number.
GPL-3
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.