Learn R Programming

MazamaCoreUtils (version 0.6.2)

stopOnError: Stop on try-error

Description

Generate a consistent error message from the result of a try() block.

Usage

stopOnError(
  result,
  err_msg = "",
  prefix = "",
  maxLength = 500,
  truncatedLength = 120,
  call. = FALSE
)

Value

Returns NULL if result is not a "try-error"; otherwise stops with an error.

Arguments

result

Return value from a try() block.

err_msg

Optional custom error message.

prefix

Optional text to prepend to the error message.

maxLength

Maximum allowed error message length before truncation.

truncatedLength

Length of the truncated error message.

call.

Logical indicating whether the call should be included in the error message. Passed to stop().

Details

This function is intended for production code where potentially fragile operations are wrapped in try(..., silent = TRUE). If result inherits from "try-error", a cleaned and optionally customized error message is generated and passed to stop().

If result is not a "try-error", the function returns NULL.

Examples

Run this code
if (FALSE) {
myFunc <- function(x) {
  log(x)
}

result <- try({
  myFunc("ten")
}, silent = TRUE)

stopOnError(result)

try({
  myFunc("ten")
}, silent = TRUE) %>%
  stopOnError(err_msg = "Unable to process user input")

try({
  myFunc("ten")
}, silent = TRUE) %>%
  stopOnError(
    prefix = "USER_INPUT_ERROR",
    maxLength = 40,
    truncatedLength = 32
  )
}

Run the code above in your browser using DataLab