3

How can we return a specific error code from plumber R API?

We would like to return a 400 status code with a message, e.g. "Feature x is missing.". We read the plumber documentation but could not figure this out.

If we use stop() a 500 Internal Server Error is returned with no specific message.

#' predict
#' @param x Input feature
#'
#' @get /predict

function(x) {
  if (is.na(x)) {
    # error code 400 should be returned
  }

 # ... # else continue with prediction
}

needRhelp
  • 2,948
  • 2
  • 24
  • 48

1 Answers1

7

It is possible for filters to return a response, you can check the doc here. For example:

#* @get /predict
function(res, req, x=NA){

    if (is.na(x)) {
        res$status <- 400  
        list(error = "Feature x is missing.")
    } else {
        # ... # else continue with prediction
    }

}
Cleptus
  • 3,446
  • 4
  • 28
  • 34
h1427096
  • 273
  • 1
  • 9
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/24202268) – Cleptus Oct 02 '19 at 11:22
  • found a link to docs for reference: https://www.rplumber.io/docs/routing-and-input.html#return-a-response Maybe new parameters look strange, but these are parameters plumber provides for api functions – h1427096 Oct 03 '19 at 07:06