How do I return an arbitrary status code with an Optional message? #2341
-
How do I return a response from an API handler with an arbitrary error status and an arbitrary error message? I currently make use of response statuses in two ways in my app, with use rocket::http::Status;
#[get("/hello1")]
pub async fn hello_any_status(
db_pool: &State<Pool>,
) -> Result<Json<String>, Status> {
...
return Err(Status::BadRequest)
} ...and in the latter case, I can pass a custom message, but the only supported error status code is use rocket::response::status;
#[get("/hello2")]
pub fn hello_with_bad_request(
db_pool: &State<Pool>,
) -> Result<Json<String>, status::BadRequest<String>> {
...
return Err(BadRequest(Some("Your name must be longer than 3 characters")))
} What's the difference between Thanks in advance 🚀 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
There are a number of options. I recommend deriving 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, |
Beta Was this translation helpful? Give feedback.
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:
Then,
ApiResponse
can be used in place ofResult
.