From 474a686f71dae4edca51a9775e3859caaf7f7597 Mon Sep 17 00:00:00 2001 From: Erik Hollensbe Date: Wed, 19 Jan 2022 16:11:09 -0800 Subject: [PATCH] Make errors an enum w/ http status, where the string form is a server error. Signed-off-by: Erik Hollensbe --- src/lib.rs | 13 ++++++++++--- src/router.rs | 6 +++--- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index e341ee6..f383935 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,11 +10,14 @@ use std::{collections::BTreeMap, pin::Pin}; pub(crate) type PinBox = Pin>; #[derive(Clone, Debug)] -pub struct Error(String); +pub enum Error { + StatusCode(http::StatusCode), + InternalServerError(String), +} impl Default for Error { fn default() -> Self { - Self(String::from("internal server error")) + Self::InternalServerError("internal server error".to_string()) } } @@ -23,7 +26,11 @@ impl Error { where T: ToString, { - Self(message.to_string()) + Self::InternalServerError(message.to_string()) + } + + pub fn new_status(error: http::StatusCode) -> Self { + Self::StatusCode(error) } } diff --git a/src/router.rs b/src/router.rs index 3360571..d56aa02 100644 --- a/src/router.rs +++ b/src/router.rs @@ -48,7 +48,7 @@ impl Route { let params = self.path.extract(provided)?; if self.method != req.method() { - return Err(Error(http::StatusCode::NOT_FOUND.to_string())); + return Err(Error::StatusCode(http::StatusCode::NOT_FOUND)); } self.handler.perform(req, None, params).await @@ -78,14 +78,14 @@ impl Router { let params = route.path.extract(path)?; let (_, response) = route.handler.perform(req, None, params).await?; if response.is_none() { - return Err(Error(http::StatusCode::INTERNAL_SERVER_ERROR.to_string())); + return Err(Error::StatusCode(http::StatusCode::INTERNAL_SERVER_ERROR)); } return Ok(response.unwrap()); } } - Err(Error(http::StatusCode::NOT_FOUND.to_string())) + Err(Error::StatusCode(http::StatusCode::NOT_FOUND)) } }