Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to set custom status code and error details for extract::error::Error #216

Open
manifest opened this issue Jul 16, 2019 · 1 comment

Comments

@manifest
Copy link
Contributor

manifest commented Jul 16, 2019

Missing value don't always assume "404 Bad Request" status code. For instance in case of authorization it would be more appropriate to return "403 Forbidden" if access token is required by the application. At the same time, some applications may want to process requests from anonymous users along with authorized ones.

impl_web! {
    impl Resource {
        #[get("/foo")]
        fn foo(&self, t: Token) -> Result<String, ()> {
            Ok(String::from("user"))
        }

        fn bar(&self, t: Option<Token>) -> Result<String, ()> {
            match t {
                Some(_) => Ok(String::from("user")),
                None => Ok(String::from("anonymous")),
            }
        }
    }
}

Currently, that is impossible to specify status code or any additional details of the extract::error::Error

struct Token;

impl<B: BufStream> Extract<B> for Token {
    type Future = Immediate<Token>;

    fn extract(context: &Context) -> Self::Future {
        match context.request().headers().get(http::header::AUTHORIZATION) {
            Some(_) => Immediate::ok(Token{}),
            None => Immediate::err(Error::missing_argument()),
        }
    }
}

The proposal is to change the extract::error::Error to make such error customization possible:

impl<B: BufStream> Extract<B> for Token {
    type Future = Immediate<Token>;

    fn extract(context: &Context) -> Self::Future {
        match context.request().headers().get(http::header::AUTHORIZATION) {
            Some(_) => Immediate::ok(Token{}),
            None => Immediate::err(Error::missing(forbidden())),
        }
    }
}

fn forbidden() -> tower_web::Error {
    tower_web::Error::from(StatusCode::FORBIDDEN)
}
@lnicola
Copy link
Collaborator

lnicola commented Sep 6, 2019

Fixed in #217.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants