Switch from "impl Responder" to Result<> response

This commit is contained in:
Tobias Reisinger 2023-11-21 15:30:30 +01:00
parent a17a9868fa
commit 09c50411d1
3 changed files with 99 additions and 133 deletions
src/handlers

View file

@ -1,24 +1,28 @@
use crate::db::errors::DatabaseError;
use actix_web::http::StatusCode;
use actix_web::HttpResponse;
use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};
use std::fmt::{Display, Formatter};
#[derive(Debug)]
pub enum HandlerError {
pub enum ApiError {
BadUid,
ProtectedSchedule,
DatabaseError(DatabaseError),
}
impl HandlerError {
impl ApiError {
fn get_code(&self) -> StatusCode {
match self {
HandlerError::BadUid => StatusCode::BAD_REQUEST,
HandlerError::ProtectedSchedule => StatusCode::FORBIDDEN,
ApiError::BadUid => StatusCode::BAD_REQUEST,
ApiError::ProtectedSchedule => StatusCode::FORBIDDEN,
ApiError::DatabaseError(db_error) => db_error.get_code(),
}
}
}
impl Serialize for HandlerError {
impl Serialize for ApiError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
@ -30,17 +34,46 @@ impl Serialize for HandlerError {
}
}
impl From<&HandlerError> for String {
fn from(err: &HandlerError) -> Self {
impl From<&ApiError> for String {
fn from(err: &ApiError) -> Self {
match err {
HandlerError::BadUid => String::from("the uid is in a bad format"),
HandlerError::ProtectedSchedule => String::from("the targeted schedule is protected"),
ApiError::BadUid => String::from("the uid is in a bad format"),
ApiError::ProtectedSchedule => String::from("the targeted schedule is protected"),
ApiError::DatabaseError(db_err) => String::from(db_err),
}
}
}
impl From<HandlerError> for HttpResponse {
fn from(err: HandlerError) -> Self {
impl From<&ApiError> for HttpResponse {
fn from(err: &ApiError) -> Self {
HttpResponse::build(err.get_code()).json(err)
}
}
impl Display for ApiError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.get_code(), String::from(self))
}
}
impl actix_web::error::ResponseError for ApiError {
fn status_code(&self) -> StatusCode {
self.get_code()
}
fn error_response(&self) -> HttpResponse {
HttpResponse::from(self)
}
}
impl From<sqlx::Error> for ApiError {
fn from(err: sqlx::Error) -> Self {
ApiError::DatabaseError(DatabaseError::from(err))
}
}
impl From<DatabaseError> for ApiError {
fn from(err: DatabaseError) -> Self {
ApiError::DatabaseError(err)
}
}