diff options
author | Quentin <quentin@deuxfleurs.fr> | 2020-11-11 13:35:02 +0100 |
---|---|---|
committer | Quentin <quentin@deuxfleurs.fr> | 2020-11-11 13:35:02 +0100 |
commit | 758e9e4e0c1304e2e9ac1a667840b63b880d1eca (patch) | |
tree | ccc01b91460b298557daf5a78362c5d993e60edf | |
parent | 045009da9b7ac4198574bd5aa256c11cfe4ae469 (diff) | |
download | garage-758e9e4e0c1304e2e9ac1a667840b63b880d1eca.tar.gz garage-758e9e4e0c1304e2e9ac1a667840b63b880d1eca.zip |
Better separate error handling and logging
Note: logging remains mixed with handler as I failed to separate it in a separate function due to the need to be executed before and after the controller.
-rw-r--r-- | src/api/api_server.rs | 24 | ||||
-rw-r--r-- | src/api/error.rs | 7 |
2 files changed, 16 insertions, 15 deletions
diff --git a/src/api/api_server.rs b/src/api/api_server.rs index ec02572d..867ab953 100644 --- a/src/api/api_server.rs +++ b/src/api/api_server.rs @@ -1,4 +1,5 @@ use std::collections::HashMap; +use std::convert::Infallible; use std::net::SocketAddr; use std::sync::Arc; @@ -50,25 +51,18 @@ async fn handler( garage: Arc<Garage>, req: Request<Body>, addr: SocketAddr, -) -> Result<Response<Body>, GarageError> { +) -> Result<Response<Body>, Infallible> { info!("{} {} {}", addr, req.method(), req.uri()); debug!("{:?}", req); - match handler_inner(garage, req).await { - Ok(x) => { - debug!("{} {:?}", x.status(), x.headers()); - Ok(x) - } - Err(e) => { - let body: Body = Body::from(format!("{}\n", e)); - let mut http_error = Response::new(body); - *http_error.status_mut() = e.http_status_code(); - warn!("Response: error {}, {}", e.http_status_code(), e); - Ok(http_error) - } - } + let res = controller(garage, req).await; + match &res { + Ok(x) => debug!("{} {:?}", x.status(), x.headers()), + Err(e) => warn!("Response: error {}, {}", e.http_status_code(), e), + }; + res.or_else(|e| Ok(e.into_http_response())) } -async fn handler_inner(garage: Arc<Garage>, req: Request<Body>) -> Result<Response<Body>, Error> { +async fn controller(garage: Arc<Garage>, req: Request<Body>) -> Result<Response<Body>, Error> { let path = req.uri().path().to_string(); let path = percent_encoding::percent_decode_str(&path).decode_utf8()?; diff --git a/src/api/error.rs b/src/api/error.rs index ddb021db..a72b7f0f 100644 --- a/src/api/error.rs +++ b/src/api/error.rs @@ -1,5 +1,6 @@ use err_derive::Error; use hyper::StatusCode; +use hyper::{Body, Response}; use garage_util::error::Error as GarageError; @@ -51,6 +52,12 @@ impl Error { _ => StatusCode::BAD_REQUEST, } } + pub fn into_http_response(&self) -> Response<Body> { + let body: Body = Body::from(format!("{}\n", self)); + let mut http_error = Response::new(body); + *http_error.status_mut() = self.http_status_code(); + http_error + } } pub trait OkOrBadRequest { |