stop_up: Stops (or warns in) sub-function execution

View source: R/misc_funs.R

stop_upR Documentation

Stops (or warns in) sub-function execution

Description

Useful if you employ non-user level sub-functions within user-level functions. When an error is thrown in the sub function, the error message will integrate the call of the user-level function, which is more informative and appropriate for the user. It offers a similar functionality for warning.

Usage

stop_up(..., up = 1, msg = NULL)

warn_up(..., up = 1, immediate. = FALSE)

Arguments

...

Objects that will be coerced to character and will compose the error message.

up

The number of frames up, default is 1. The call in the error message will be based on the function up frames up the stack. See examples. If you have many calls to stop_up/warn_up with a value of up different than one, you can use set_up to change the default value of up within the function.

msg

A character vector, default is NULL. If provided, this message will be displayed right under the error message. This is mostly useful when the text contains formatting because the function stop used to send the error message erases any formatting.

immediate.

Whether the warning message should be prompted directly. Defaults to FALSE.

Details

These functions are really made for package developers to facilitate the good practice of providing informative user-level error/warning messages.

Functions

  • warn_up: Warnings at the level of user-level functions

Author(s)

Laurent Berge

Examples


# We create a main user-level function
# The computation is done by an internal function
# Here we compare stop_up with a regular stop

main_function = function(x = 1, y = 2){
  my_internal_function(x, y)
}

my_internal_function = function(x, y){
  if(!is.numeric(x)){
    stop_up("Argument 'x' must be numeric but currently isn't.")
  }

  # Now regular stop
  if(!is.numeric(y)){
    stop("Argument 'y' must be numeric but currently isn't.")
  }

  nx = length(x)
  ny = length(y)
  if(nx != ny){
    warn_up("The lengths of x and y don't match (", nx, " vs ", ny, ").")
  }

  x + y
}

# Let's compare the two error messages
# stop_up:
try(main_function(x = "a"))
# => the user understands that the problem is with x

# Now compare with the regular stop:
try(main_function(y = "a"))
# Since the user has no clue of what my_internal_function is,
#  s/he will be puzzled of what to do to sort this out

# Same with the warning => much clearer with warn_up
main_function(1, 1:2)



dreamerr documentation built on Aug. 24, 2023, 1:08 a.m.