Customizing errors from Query extractor in Rust with Axum.

huangapple go评论70阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月22日 09:41:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302607.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定