Skip to content

Commit

Permalink
Merge pull request #64 from kennedymwavu/ft-create-error-handler-method
Browse files Browse the repository at this point in the history
ft: create error handler method
  • Loading branch information
JohnCoene authored Mar 10, 2024
2 parents 7127b59 + 4d26e3f commit 0aba170
Show file tree
Hide file tree
Showing 3 changed files with 141 additions and 0 deletions.
39 changes: 39 additions & 0 deletions R/ambiorix.R
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,45 @@ Ambiorix <- R6::R6Class(
self$not_found <- handler
invisible(self)
},
#' @details Sets the error handler.
#' @param handler Function that accepts a request, response and an error object.
#'
#' @examples
#' # my custom error handler:
#' error_handler <- \(req, res, error) {
#' if (!is.null(error)) {
#' error_msg <- conditionMessage(error)
#' cli::cli_alert_danger("Error: {error_msg}")
#' }
#' response <- list(
#' code = 500L,
#' msg = "Uhhmmm... Looks like there's an error from our side :("
#' )
#' res$
#' set_status(500L)$
#' json(response)
#' }
#'
#' # handler for GET at /whoami:
#' whoami <- \(req, res) {
#' # simulate error (object 'Pikachu' is not defined)
#' print(Pikachu)
#' }
#'
#' app <- Ambiorix$
#' new()$
#' set_error(error_handler)$
#' get("/whoami", whoami)
#'
#' if (interactive()) {
#' app$start(open = FALSE)
#' }
set_error = function(handler) {
assert_that(not_missing(handler))
assert_that(is_error_handler(handler))
self$error <- handler
invisible(self)
},
#' @details Static directories
#'
#' @param path Local path to directory of assets.
Expand Down
11 changes: 11 additions & 0 deletions R/assertions.R
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,17 @@ assertthat::on_failure(is_handler) <- function(call, env){
paste("`handler` must be a function that accepts: `req`, and `res`")
}

is_error_handler <- function(x) {
is_fun <- is.function(x)
has_args <- length(formalArgs(x)) == 3

all(is_fun, has_args)
}

assertthat::on_failure(is_error_handler) <- function(call, env) {
"`handler` must be a function that accepts: `req`, `res` and `error`"
}

is_logger <- function(x){
inherits(x, "Logger")
}
Expand Down
91 changes: 91 additions & 0 deletions man/Ambiorix.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 0aba170

Please sign in to comment.