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

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

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().

Value

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

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.

Note

If logging has been initialized, the final error message is logged with logger.error() before calling stop().

Examples

if (FALSE) { # \dontrun{
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
  )
} # }