Rocket icon indicating copy to clipboard operation
Rocket copied to clipboard

[Feature Request] Allow catchers to specify the format they respond to

Open rokob opened this issue 8 years ago • 2 comments

Allow catchers to specify a format just like other routes do. For example, I expected the following to work:

#[get("/user", format="application/json")]
pub fn user() -> Json<User> {
    ...
}

#[catch(404, format="application/json")]
fn not_found_json(req: &Request) -> Json {
    let resp = Json(json!({...}));
    NotFound(resp)
}

#[catch(404)]
fn not_found(req: &Request) -> Template {
    let mut map = HashMap::new();
    map.insert("path", req.uri().as_str());
    Template::render("error/404", &map)
}
  1. Why you believe this feature is necessary.

When a client makes a request with an Accept header of application/json to a non-existent resource, it is not desirable to return an HTML 404 page. Rather, one would like to return a body that conforms to the Accept header of the request. Similarly for requests with a body with a Content-Type that is not HTML.

  1. A convincing use-case for this feature.

Any API that wants to read/write more than one format and handle errors in each format.

  1. Why this feature can't or shouldn't exist outside of Rocket.

One can handle this today by introspecting on the request and kind of make this work today, but it is inconsistent with the standard route syntax and does not seem to jive with the Rocket way of doing things via guards.

I can put up a PR for this and see if it makes sense if there is any interest.

rokob avatar Oct 12 '17 06:10 rokob

Before this feature gets implemented, is there any way to disable default error catchers? So the clients can get 'raw' response.

weiwei-lin avatar Mar 15 '18 12:03 weiwei-lin

At the moment, handling errors is a lot different from handling a normal route. Maybe it would be more fitting for the definition of Route to include:

pub struct Route {
    pub error: Option<u16>, 
} 

And so the route is only used when there is an error.

If this was defined, it would give the lowest rank by default (used first)

DJMcNab avatar Mar 15 '18 13:03 DJMcNab