Replies: 1 comment 3 replies
-
You can implement you own custom responder around #[derive(Responder)]
#[response(status = 400)] // That will depend on your use-case
struct ErrorTemplate(Template); Then implement impl From<ParseIntError> for ErrorTemplate {
fn from(err: ParseIntError) -> Self {
Self(Template::render("message", context! { message: format!("not a number {err}") })))
}
} You can do this for multiple errors, but be consistent with the HTTP status code you chose previously. If you want to support multiple status codes, add a field to This ultimately allows you to use the try ( #[get("/number/<number>")]
fn number(number: &str) -> Result<Template, ErrorTemplate> {
let number = number.parse::<i32>()?;
Ok(Template::render("number", context! { number }))
} This is how I always do my error management with Rocket. |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I seem to have many cases when in the route I need to check certain things, if they fail I might want to return an error message and only if all of them passed I would do some more processing. I included a minimal example where I know I could have just defined the expected parameter to be
u32
, but it seems to a simple example.In the first implementation (called deep) I'd check each condition with a
match
and in theOk
arm I'd go deeper and deeper. Not nice.The second implementation (early return using match) looks better but I feel I still have lots of unnecessary code.
In the 3rd implementation I return a
Result<Template, Template>
.I wonder if this seems like a correct way to handle the situation or if there is a better way?
Beta Was this translation helpful? Give feedback.
All reactions