Jonathan Rauscher
Jonathan Rauscher

Reputation: 157

R plumber return error and object from env in response payload

I'm currently building an API service in R using plumber. I was wondering if a function within my app errors out, is there a way to tryCatch it in such a way that I can return both the error itself and an object that exists in the environment at the time of the error? Any help is greatly appreciated.

Upvotes: 1

Views: 981

Answers (1)

Bruno Tremblay
Bruno Tremblay

Reputation: 776

Short answer yes, provide same samples so it is possible to build something around it.

Longer answer : this is the default error handler

defaultErrorHandler <- function(){
  function(req, res, err){
    print(err)

    li <- list()

    if (res$status == 200L){
      # The default is a 200. If that's still set, then we should probably override with a 500.
      # It's possible, however, than a handler set a 40x and then wants to use this function to
      # render an error, though.
      res$status <- 500
      li$error <- "500 - Internal server error"
    } else {
      li$error <- "Internal error"
    }


    # Don't overly leak data unless they opt-in
    if (getOption("plumber.debug", FALSE)) {
      li["message"] <- as.character(err)
    }

    li
  }
}

As you can see towards the ends, you can use the plumber.debug option to return more information about the error. What you can also do is provide your own error handler.

pr <- plumb("plumber.R")
yourErrorHandler <- function(){
  function(req, res, err, ...){
    #do stuff, set res status you want
  }
}
pr$setErrorHandler(fun = yourErrorHandler)

Documentation seems to be lacking at moment for this subject. https://www.rplumber.io/docs/rendering-and-output.html#error-handling

Upvotes: 1

Related Questions