diff options
author | Martin Fischer <martin@push-f.com> | 2021-01-22 21:34:35 +0100 |
---|---|---|
committer | Martin Fischer <martin@push-f.com> | 2021-01-22 21:36:53 +0100 |
commit | 4ba2d050bdf1a3c0070f3aa2331c82745611af1f (patch) | |
tree | 710b2d96dba397da5d5888f5099402f6271dc9fd /examples/csrf/src | |
parent | b886de1afc0b90d7ca27db9d5c7dabddbe3d7ee0 (diff) |
completely ditch Sputnik's general Error type
Users also want to short-circuit error types from other crates but they
cannot define a From conversion between two foreign types.
Sputnik's error type also didn't allow for proper error logging.
bump version to 0.2.3
Diffstat (limited to 'examples/csrf/src')
-rw-r--r-- | examples/csrf/src/main.rs | 32 |
1 files changed, 23 insertions, 9 deletions
diff --git a/examples/csrf/src/main.rs b/examples/csrf/src/main.rs index 497bd66..915d063 100644 --- a/examples/csrf/src/main.rs +++ b/examples/csrf/src/main.rs @@ -1,15 +1,31 @@ use std::convert::Infallible; use hyper::service::{service_fn, make_service_fn}; -use hyper::{Method, Server}; +use hyper::{Method, Server, StatusCode}; use serde::Deserialize; use sputnik::security::CsrfToken; -use sputnik::{Error, request::{Parts, Body}, response::Response}; +use sputnik::{request::{Parts, Body}, response::Response}; +use sputnik::request::error::*; + +#[derive(thiserror::Error, Debug)] +enum Error { + #[error("page not found")] + NotFound(String), + #[error("{0}")] + CsrfError(#[from] CsrfProtectedFormError) +} + +fn render_error(err: Error) -> (StatusCode, String) { + match err { + Error::NotFound(msg) => (StatusCode::NOT_FOUND, msg), + Error::CsrfError(err) => (StatusCode::BAD_REQUEST, err.to_string()), + } +} async fn route(req: &mut Parts, body: Body) -> Result<Response,Error> { match (req.method(), req.uri().path()) { (&Method::GET, "/form") => get_form(req).await, (&Method::POST, "/form") => post_form(req, body).await, - _ => return Err(Error::not_found("page not found".to_owned())) + _ => return Err(Error::NotFound("page not found".to_owned())) } } @@ -37,12 +53,10 @@ async fn service(req: hyper::Request<hyper::Body>) -> Result<hyper::Response<hyp let (mut parts, body) = sputnik::request::adapt(req); match route(&mut parts, body).await { Ok(res) => Ok(res.into()), - Err(err) => match err { - Error::Simple(err) => { - Ok(err.response_builder().body(err.message.into()).unwrap()) - // you can easily wrap or log errors here - } - Error::Response(err) => Ok(err) + Err(err) => { + let (code, message) = render_error(err); + // you can easily wrap or log errors here + Ok(hyper::Response::builder().status(code).body(message.into()).unwrap()) } } } |