Module warp::reject

source ·
Expand description

Rejections

Part of the power of the Filter system is being able to reject a request from a filter chain. This allows for filters to be combined with or, so that if one side of the chain finds that a request doesn’t fulfill its requirements, the other side can try to process the request.

Many of the built-in filters will automatically reject the request with an appropriate rejection. However, you can also build new custom Filters and still want other routes to be matchable in the case a predicate doesn’t hold.

As a request is processed by a Filter chain, the rejections are accumulated into a list contained by the Rejection type. Rejections from filters can be handled using Filter::recover. This is a convenient way to map rejections into a Reply.

For a more complete example see the Rejection Example from the repository.

§Example

use warp::{reply, Reply, Filter, reject, Rejection, http::StatusCode};

#[derive(Debug)]
struct InvalidParameter;

impl reject::Reject for InvalidParameter {}

// Custom rejection handler that maps rejections into responses.
async fn handle_rejection(err: Rejection) -> Result<impl Reply, std::convert::Infallible> {
    if err.is_not_found() {
        Ok(reply::with_status("NOT_FOUND", StatusCode::NOT_FOUND))
    } else if let Some(e) = err.find::<InvalidParameter>() {
        Ok(reply::with_status("BAD_REQUEST", StatusCode::BAD_REQUEST))
    } else {
        eprintln!("unhandled rejection: {:?}", err);
        Ok(reply::with_status("INTERNAL_SERVER_ERROR", StatusCode::INTERNAL_SERVER_ERROR))
    }
}


// Filter on `/:id`, but reject with InvalidParameter if the `id` is `0`.
// Recover from this rejection using a custom rejection handler.
let route = warp::path::param()
    .and_then(|id: u32| async move {
        if id == 0 {
            Err(warp::reject::custom(InvalidParameter))
        } else {
            Ok("id is valid")
        }
    })
    .recover(handle_rejection);

Modules§

Macros§

Structs§

Enums§

Traits§

  • Cause 🔒
  • A marker trait to ensure proper types are used for custom rejections.

Functions§