From 83ba68a8b70538d80fdbd56669cac0950aa4c174 Mon Sep 17 00:00:00 2001 From: Jonas_Jones <91549607+J-onasJones@users.noreply.github.com> Date: Fri, 15 Dec 2023 03:30:43 +0100 Subject: [PATCH] Implemented new Error handling system New Error Handling System with custom errors and JSON Error responses --- src/error_responses.rs | 28 ++++++++++++++++++++++++++++ src/main.rs | 1 + src/server.rs | 25 ++++++++++++++++++++++++- 3 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 src/error_responses.rs diff --git a/src/error_responses.rs b/src/error_responses.rs new file mode 100644 index 0000000..792e4d5 --- /dev/null +++ b/src/error_responses.rs @@ -0,0 +1,28 @@ +use serde::Serialize; + +#[derive(Serialize)] +pub struct ErrorMessage { + pub(crate) code: u16, + pub(crate) message: String, +} + +#[derive(Debug)] +pub struct InternalServerError; +impl warp::reject::Reject for InternalServerError {} + +#[derive(Debug)] +pub struct BadRequestError; +impl warp::reject::Reject for BadRequestError {} + +#[derive(Debug)] +pub struct NotFoundError; +impl warp::reject::Reject for NotFoundError {} + +#[derive(Debug)] +pub struct UnauthorizedError; +impl warp::reject::Reject for UnauthorizedError {} + +#[derive(Debug)] +pub struct ForbiddenError; +impl warp::reject::Reject for ForbiddenError {} + diff --git a/src/main.rs b/src/main.rs index f05dd0a..86eb624 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,7 @@ pub mod v1; pub mod logger; pub mod tools; pub mod server; +pub mod error_responses; pub use logger::Logger; pub use tools::parse_ip; diff --git a/src/server.rs b/src/server.rs index 4b01832..f0a0d21 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1,7 +1,11 @@ +use std::convert::Infallible; use std::env; +use reqwest::StatusCode; use warp::Filter; +use warp::reply::Reply; +use crate::error_responses::{ErrorMessage, InternalServerError, BadRequestError, NotFoundError}; use crate::v1::get_v1_routes; use crate::{Logger, parse_ip}; @@ -16,8 +20,27 @@ pub async fn serve() { // GET (any) => reply with return from handle_path let routes = get_v1_routes() - .or(warp::any().map(|| warp::reply::with_status("Not Found", warp::http::StatusCode::NOT_FOUND))); + .recover(handle_rejection); + + async fn handle_rejection(err: warp::Rejection) -> Result { + let (code, message) = if err.find::().is_some() { + (StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL_SERVER_ERROR") + } else if err.find::().is_some() { + (StatusCode::BAD_REQUEST, "BAD_REQUEST") + } else if err.is_not_found() || err.find::().is_some() { + (StatusCode::NOT_FOUND, "NOT_FOUND") + } else { + (StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL_SERVER_ERROR") // Default case + }; + + let json = warp::reply::json(&ErrorMessage { + code: code.as_u16(), + message: message.into(), + }); + + Ok(warp::reply::with_status(json, code)) + } warp::serve(routes)