refactor
This commit is contained in:
41
backend/src/error.rs
Normal file
41
backend/src/error.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use axum::{
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
|
||||
use crate::models::ErrorResponse;
|
||||
|
||||
pub enum AppError {
|
||||
Unauthorized,
|
||||
NotFound(String),
|
||||
BadRequest(String),
|
||||
Internal(String, Option<String>),
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
fn into_response(self) -> Response {
|
||||
let (status, error_message, details) = match self {
|
||||
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "Unauthorized".to_string(), None),
|
||||
AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg, None),
|
||||
AppError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg, None),
|
||||
AppError::Internal(msg, details) => (StatusCode::INTERNAL_SERVER_ERROR, msg, details),
|
||||
};
|
||||
|
||||
let body = Json(ErrorResponse {
|
||||
error: error_message,
|
||||
details,
|
||||
});
|
||||
|
||||
(status, body).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> From<E> for AppError
|
||||
where
|
||||
E: std::error::Error + Send + Sync + 'static,
|
||||
{
|
||||
fn from(err: E) -> Self {
|
||||
AppError::Internal("Internal Server Error".to_string(), Some(err.to_string()))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user