From 09df210c172790fe5ed0331e4213af858096ba69 Mon Sep 17 00:00:00 2001 From: xmppftw Date: Wed, 7 Aug 2024 11:11:31 +0200 Subject: [PATCH] Add per-error HTTP status code --- src/error.rs | 18 +++++++++++++++++- src/web.rs | 4 ++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/error.rs b/src/error.rs index 361a813..e45c86a 100644 --- a/src/error.rs +++ b/src/error.rs @@ -20,6 +20,7 @@ use std::str::Utf8Error; use hex::FromHexError; use hmac::digest::InvalidLength as HmacInvalidLength; +use hyper::StatusCode; #[derive(Debug)] pub(crate) enum Error { @@ -38,12 +39,27 @@ pub(crate) enum Error { Var(VarError), } +impl Error { + pub fn status(&self) -> StatusCode { + match self { + Self::MethodMismatch(_) => StatusCode::METHOD_NOT_ALLOWED, + Self::InvalidSecret => StatusCode::FORBIDDEN, + Self::InvalidContentType => StatusCode::UNSUPPORTED_MEDIA_TYPE, + Self::InvalidSignature => StatusCode::FORBIDDEN, + Self::InvalidRequest => StatusCode::BAD_REQUEST, + _ => StatusCode::INTERNAL_SERVER_ERROR, + } + } +} + impl StdError for Error {} impl std::fmt::Display for Error { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { match self { - Error::MethodMismatch(method) => write!(fmt, "method is invalid {method}, expected POST"), + Error::MethodMismatch(method) => { + write!(fmt, "method is invalid {method}, expected POST") + } Error::InvalidSecret => write!(fmt, "the secret is invalid"), Error::InvalidContentType => write!(fmt, "the content-type is invalid"), Error::InvalidSignature => write!(fmt, "the signature is invalid"), diff --git a/src/web.rs b/src/web.rs index 499f186..1899ba0 100644 --- a/src/web.rs +++ b/src/web.rs @@ -30,12 +30,12 @@ use tokio::sync::mpsc::UnboundedSender; type HmacSha256 = Hmac; -fn error_res(e: E) -> Result>, Infallible> { +fn error_res(e: Error) -> Result>, Infallible> { error!("error response: {:?}", e); let text = format!("{:?}", e); let res = Response::builder() - .status(200) + .status(e.status()) .body(Full::new(Bytes::from(text))) .unwrap(); Ok(res)