From 3bc7cf8ed36016ca3da9438a98f4fe8b8e6f9e61 Mon Sep 17 00:00:00 2001 From: FxQnLr Date: Thu, 15 Feb 2024 17:17:30 +0100 Subject: Closes #10 & #12. Added `thiserror` crate and changed to `IntoSocketAddr` for easier usage and error handling --- src/error.rs | 65 +++++++++++++++++++++++++++++++++++++----------------------- 1 file changed, 40 insertions(+), 25 deletions(-) (limited to 'src/error.rs') diff --git a/src/error.rs b/src/error.rs index 56d6c52..4f1bedd 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,44 +1,59 @@ -use std::io; +use crate::auth::Error as AuthError; use axum::http::StatusCode; -use axum::Json; use axum::response::{IntoResponse, Response}; +use axum::Json; use serde_json::json; +use std::io; use tracing::error; -use crate::auth::Error as AuthError; -#[derive(Debug)] +#[derive(Debug, thiserror::Error)] pub enum Error { + #[error("generic error")] Generic, - Auth(AuthError), - DB(sqlx::Error), - IpParse(::Err), - BufferParse(std::num::ParseIntError), - Broadcast(io::Error), + + #[error("auth: {source}")] + Auth { + #[from] + source: AuthError, + }, + + #[error("db: {source}")] + Db { + #[from] + source: sqlx::Error, + }, + + #[error("buffer parse: {source}")] + ParseInt { + #[from] + source: std::num::ParseIntError, + }, + + #[error("io: {source}")] + Io { + #[from] + source: io::Error, + }, } impl IntoResponse for Error { fn into_response(self) -> Response { + error!("{}", self.to_string()); let (status, error_message) = match self { - Self::Auth(err) => { - err.get() - }, + Self::Auth { source } => source.get(), Self::Generic => (StatusCode::INTERNAL_SERVER_ERROR, ""), - Self::IpParse(err) => { - error!("server error: {}", err.to_string()); - (StatusCode::INTERNAL_SERVER_ERROR, "Server Error") - }, - Self::DB(err) => { - error!("server error: {}", err.to_string()); + Self::Db { source } => { + error!("{source}"); (StatusCode::INTERNAL_SERVER_ERROR, "Server Error") - }, - Self::Broadcast(err) => { - error!("server error: {}", err.to_string()); + } + Self::Io { source } => { + error!("{source}"); (StatusCode::INTERNAL_SERVER_ERROR, "Server Error") - }, - Self::BufferParse(err) => { - error!("server error: {}", err.to_string()); + } + Self::ParseInt { source } => { + error!("{source}"); (StatusCode::INTERNAL_SERVER_ERROR, "Server Error") - }, + } }; let body = Json(json!({ "error": error_message, -- cgit v1.2.3