Implemented new Error handling system

New Error Handling System with custom errors and JSON Error responses
This commit is contained in:
Jonas_Jones 2023-12-15 03:30:43 +01:00
parent 4357786edc
commit 83ba68a8b7
3 changed files with 53 additions and 1 deletions

28
src/error_responses.rs Normal file
View file

@ -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 {}

View file

@ -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;

View file

@ -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<impl Reply, Infallible> {
let (code, message) = if err.find::<InternalServerError>().is_some() {
(StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL_SERVER_ERROR")
} else if err.find::<BadRequestError>().is_some() {
(StatusCode::BAD_REQUEST, "BAD_REQUEST")
} else if err.is_not_found() || err.find::<NotFoundError>().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)