Skip to content

Error Handling Examples #388

@bradfier

Description

@bradfier

It's possible I'm just not following the rejections example well enough, but what is the correct way of indicating that a handler (called with and_then()) is fallible, and returning the error from that method in a reply?

For an example of the behaviour I'm trying to replicate, in Actix or Rouille, handler functions are defined as returning something resembling a Result<GoodReply, BadReply>, both of which can be expected to produce an HTTP response.

e.g a simple index handler which should generate a 500 if the templating fails:

async fn index(tmpl: web::Data<tera::Tera>) -> Result<HttpResponse, Error> {
    let html = tmpl
        .render("index.html", &tera::Context::new())
        .map_err(|_| HttpResponse::InternalServerError("Failed to render template")))?;

    Ok(HttpResponse::Ok().body(html))
}

Reading the docs for Warp, it seems like a Rejection should be used to indicate that this filter could not or should not accept the request, is this the case? And if so, is there an idiomatic way to replicate the behaviour I've sketched above? I can go down the road of matching on results from fallible functions in my handlers, and doing an early return warp::reply(...), but then I lose out on the ergonomics offered by the ? operator inside the function.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions