Skip to content

How do I return an arbitrary status code with an Optional message? #2341

Discussion options

You must be logged in to vote

There are a number of options. I recommend deriving Responder on an enum, which allows you to set a custom status & responder. For a simple case, you can return (http::Status, R), where R implements Responder. This will set the status code and return the content of R.

The enum case should looks something like:

#[derive(Responder)]
pub enum ApiResponse<T> {
  Ok(T),
  #[response(status = 400)]
  BadRequest(String),
  #[response(status = 401)]
  Unauthorized(String),
  #[response(status = 403)]
  Forbidden(String),
}

Then, ApiResponse can be used in place of Result.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by thomasmost
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants