I want to match my error messages on the basis of the status codes I get from my endpoint
// error message enum
#[derive(Serialize, Deserialize, ToSchema, Clone, Debug)]
pub enum ErrorResponse {
/// When item is not found from storage.
NotFound(String),
/// When unauthorized to complete operation
Unauthorized(String),
/// The server cannot process the request due to a client error
BadRequest(String),
/// The client does not have access to the content
Forbidden(String),
/// The request was well-formed but was unable to be followed due to semantic errors
UnprocessableContent(String),
/// The server encountered an unexpected condition that prevented it from fulfilling the request
InternalServerError(String),
BadGateway(String)
}
// one of my endpoints
#[get("/statistics/all")]
pub async fn get_all_statistics() -> Result<HttpResponse, ErrorResponse> {
//TODO: writing a service function that calculates statistic data
let cache: RedisCache = RedisCache::default();
let vec: Vec<String> = vec![cache.get_str("statistics").await.unwrap()];
Ok(HttpResponse::Ok().json(vec))
}
How can I change my endpoint or create a function that handles the response based on the given status code? I cannot find an actix function like get_status_code().
I can only find actix_web::dev::ServiceResponse that can be used as a wrapper but I cannot figure out how to use it correctly.
You get access to the service response in your middleware. You could create your ErrorMessage there, though I personally would just return it from your endpoints directly instead of ErrorResponse, I don't see a need for both types as the former is just the latter in more specific.
Maybe more specific: if I have 401, 404, and 200 how can I set my response messages? I cannot find a way to manipulate multiple HTTP responses. Two at most.
Where is the status_code variable in your endpoint coming from? Don't you decide what it is? You can match multiple patterns in one match arm with |, i.e. 401 | 402 => {}.