How to get some useful datas when returning Result
in async fn.
#2097
-
In the error_handling docs, the best way for returning error from use axum::http::StatusCode;
async fn handler() -> Result<String, StatusCode> {
Err(StatusCode::NOT_FOUND)
} In my application ,I defined a struct represents errors, and impl IntoResponse for it: #[derive(Debug,Clone,serde::Serialize)]
struct MyError{
message: String,
// ... something else
}
impl IntoResponse for MyError{
fn into_response(self) -> Response {
(StatusCode::INTERNAL_SERVER_ERROR, Json(self)).into_response()
}
} Now, I want to return either Json or Html in MyError based on whether the request is sent by xhr. I found that I can't get any information abount request in MyError unless I pass to it: #[derive(Debug,Clone,serde::Serialize)]
struct MyError{
message: String,
should_html: bool,
// ... something else
}
// In async fn
// I defined a extractor here to judge if this request is made by xhr
async fn handler(IsXhr(is_xhr): IsXhr) -> Result<String, MyError> {
Err(MyError{
message: String::from("Something went wrong"),
should_html: is_xhr
})
} Is this the only way I can do? Is there a method that does not require every async fn to judge whether it needs to return html? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Yep that's the only way. |
Beta Was this translation helpful? Give feedback.
Yep that's the only way.
IntoResponse
intentionally doesn't get access to the request data as that makes calling the.into_response()
method inside handlers hard. I actually spoke about this during a talk I gave recently https://youtu.be/w1atdqNsA80?t=2013