英文:
Customizing errors from Query extractor in Rust with Axum
问题
I have followed the example provided here to customize the extractor error for the Json
extractor:
#[derive(FromRequest)]
#[from_request(via(axum::Json), rejection(ApiError))]
pub struct JsonExtractor<T>(pub T);
#[axum::debug_handler]
pub(crate) async fn create(
state: State<AppState>,
JsonExtractor(json): JsonExtractor<RouteBody>,
) -> Result<axum::Json<Customer>, ApiError>
This works great, but when I try the same for extracting from the Query, I get errors:
#[derive(FromRequest)]
#[from_request(via(axum::extract::Query), rejection(ApiError))]
pub struct QueryExtractor<T>(pub T);
#[axum::debug_handler]
pub(crate) async fn list(
state: State<AppState>,
query: QueryExtractor<RouteQuery>, // errors here
) -> Result<axum::Json<List<Customer>>, ApiError>
the trait bound `QueryExtractor<customers::list::RouteQuery>: FromRequest<AppState, hyper::Body, _>` is not satisfied
Function argument is not a valid axum extractor.
英文:
I have followed the example provided here to customize the extractor error for the Json
extractor:
#[derive(FromRequest)]
#[from_request(via(axum::Json), rejection(ApiError))]
pub struct JsonExtractor<T>(pub T);
#[axum::debug_handler]
pub(crate) async fn create(
state: State<AppState>,
JsonExtractor(json): JsonExtractor<RouteBody>,
) -> Result<axum::Json<Customer>, ApiError>
This works great, but when I try the same for extracting from the Query, I get errors:
#[derive(FromRequest)]
#[from_request(via(axum::extract::Query), rejection(ApiError))]
pub struct QueryExtractor<T>(pub T);
#[axum::debug_handler]
pub(crate) async fn list(
state: State<AppState>,
query: QueryExtractor<RouteQuery>, // errors here
) -> Result<axum::Json<List<Customer>>, ApiError>
the trait bound `QueryExtractor<customers::list::RouteQuery>: FromRequest<AppState, hyper::Body, _>` is not satisfied
Function argument is not a valid axum extractor.
答案1
得分: 3
差异在于Json
实现了FromRequest
,而Query
实现了FromRequestParts
(后者不会消耗请求体)。
因此,您应该使用#[derive(FromRequestParts)
:
这与
#[derive(FromRequest)]
类似,只是它使用FromRequestParts
。所有相同的选项都受支持。
英文:
The difference is Json
implements FromRequest
while Query
implements FromRequestParts
(the latter doesn't consume the request body).
So you'd use #[derive(FromRequestParts)
instead:
> This works similarly to #[derive(FromRequest)]
except it uses FromRequestParts
. All the same options are supported.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论