R/check_for_status.R

#' check_for_status
#'
#' @param type character, one of "error", "warning", "message"
#' @param message_function function, builds message,
#'   takes \code{x} as first arguement, \code{...} as additional arguements.
#'   Default is a standard message function.
#' @param ... additional arguements for \code{message_function}
#'
#' @return If request was successful, an invisible TRUE.
#'    Otherwise, raised a classed http error or warning, as generated by \code{http_condition}
#' @examples
#'   x <- httr::GET("http://httpbin.org/status/404")
#'   check_for_status(x, type = "error", message_function = message_verbose)
#'
#' @export
#'
check_for_status <- function(
  x, type = "error", message_function = message_standard, ...){

  # validate type
  type <- match.arg(type, c("error", "warning", "message"))

  # check to see if we can return without doing anything
  if (httr:::successful(x)) return(invisible(TRUE))

  # define the possible actions
  action <- list(error = stop, warning = warning, message = message)

  # build the message
  msg <- message_function(x, ...)

  # act
  action[[type]](httr::http_condition(x, type, message = msg, call = sys.call(-1)))

}
ijlyttle/httrplus documentation built on May 18, 2019, 3:41 a.m.