Created
November 3, 2021 16:42
-
-
Save meredian/9dff0dc056fc4c3e61252576ae86a41b to your computer and use it in GitHub Desktop.
One more example how to override warp's problem with having lowest priority for rejection::not_found (so it starts looking into other branches and often results in e.g. 405 METHOD NOT ALLOWED)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Define custom error enum, | |
pub enum Error { | |
NotFound() | |
// ... and any more errors here | |
} | |
// Make it castable to Rejection | |
impl warp::reject::Reject for Error {} | |
pub async fn handler() -> std::result::Result<impl Reply, Rejection> { | |
let user = db::get_user(&db_pool, id).await?; | |
match user { | |
Some(user) => Ok(json(&UserUpdateResponse::of(user))), | |
None => Err(Error::NotFound().into()) | |
} | |
} | |
pub async fn handle_rejection(err: Rejection) -> Result<impl Reply, Infallible> { | |
let code; | |
if err.is_not_found() { | |
code = StatusCode::NOT_FOUND; | |
message = "Not Found"; | |
} else if let Some(e) = err.find::<Error>() { | |
match e { | |
// On rejection we force this custom branch, not err.is_not_foun() | |
Error::NotFound() => { | |
code = StatusCode::NOT_FOUND; | |
message = "Not Found"; | |
} | |
_ => { | |
code = StatusCode::INTERNAL_SERVER_ERROR; | |
} | |
} | |
} else { | |
code = StatusCode::INTERNAL_SERVER_ERROR; | |
} | |
Ok(code) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment