Skip to content

Commit

Permalink
Gracefully handle missing headers
Browse files Browse the repository at this point in the history
Reports a missing header rejection only if the header's decoder didn't return a default value.

Closes tokio-rs#1781.
  • Loading branch information
RReverser committed Mar 3, 2023
1 parent 7947d13 commit 48fe6f1
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions axum/src/typed_header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,19 @@ where
type Rejection = TypedHeaderRejection;

async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
match parts.headers.typed_try_get::<T>() {
Ok(Some(value)) => Ok(Self(value)),
Ok(None) => Err(TypedHeaderRejection {
let mut values = parts.headers.get_all(T::name()).iter();
let is_missing = values.size_hint() == (0, Some(0));
T::decode(&mut values)
.map(Self)
.map_err(|err| TypedHeaderRejection {
name: T::name(),
reason: TypedHeaderRejectionReason::Missing,
}),
Err(err) => Err(TypedHeaderRejection {
name: T::name(),
reason: TypedHeaderRejectionReason::Error(err),
}),
}
reason: if is_missing {
// Report a more precise rejection for the missing header case.
TypedHeaderRejectionReason::Missing
} else {
TypedHeaderRejectionReason::Error(err)
},
})
}
}

Expand Down

0 comments on commit 48fe6f1

Please sign in to comment.