Skip to content

Commit

Permalink
Param filter with user-defined rejection
Browse files Browse the repository at this point in the history
  • Loading branch information
hwchen committed Oct 28, 2019
1 parent 5c26956 commit fb1ec58
Showing 1 changed file with 45 additions and 9 deletions.
54 changes: 45 additions & 9 deletions src/filters/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,23 +250,59 @@ pub fn param<T: FromStr + Send + 'static>() -> impl Filter<Extract = One<T>, Err
/// segment, and if successful, the value is returned as the `Filter`'s
/// "extracted" value.
///
/// If the value could not be parsed, rejects with a `404 Not Found`. In
/// contrast of `param` method, it reports an error cause in response.
/// If the value could not be parsed, rejects with a user-defined [`Rejection`][].
///
/// The associated `Err` on the `FromStr` must impl `From` for `Rejection`. See example.
///
/// If [`warp::reject::custom`][] is used to create a `Rejection`, a [`recover`][] filter
/// should convert this `Rejection` into a `Reply`, or else this will be returned as a
/// `500 Internal Server Error`.
///
/// [`Rejection`]: ../../reject/struct.Rejection.html
/// [`recover`]: ../trait.Filter.html#method.recover
/// [`warp::reject::custom`]: ../../reject/fn.custom.html
///
///
/// # Example
///
/// ```
/// use warp::Filter;
/// use std::convert::From;
/// use std::str::FromStr;
/// use warp::{Filter, Rejection};
///
/// let route = warp::path::param2()
/// .map(|id: u32| {
/// format!("You asked for /{}", id)
/// #[derive(Debug)]
/// struct MyStruct {
/// id: u32,
/// }
///
/// impl FromStr for MyStruct {
/// type Err = MyError;
///
/// fn from_str(s: &str) -> Result<Self, Self::Err> {
/// let id = s.parse::<u32>().map_err(|_| MyError)?;
///
/// Ok(MyStruct { id })
/// }
/// }
///
/// struct MyError;
///
/// impl From<MyError> for Rejection {
/// fn from(err: MyError) -> Rejection {
/// warp::reject::custom("My Custom Rejection")
/// }
/// }
///
/// let route = warp::path::param_with_err()
/// .map(|id: MyStruct| {
/// format!("You asked for /{:?}", id)
/// });
///
/// ```
pub fn param2<T>() -> impl Filter<Extract = One<T>, Error = Rejection> + Copy
pub fn param_with_err<T>() -> impl Filter<Extract = One<T>, Error = Rejection> + Copy
where
T: FromStr + Send + 'static,
T::Err: Into<crate::reject::Cause>,
T::Err: Into<Rejection>,
{
segment(|seg| {
log::trace!("param?: {:?}", seg);
Expand All @@ -275,7 +311,7 @@ where
}
T::from_str(seg).map(one).map_err(|err| {
#[allow(deprecated)]
reject::not_found().with(err.into())
err.into()
})
})
}
Expand Down

0 comments on commit fb1ec58

Please sign in to comment.