Files
libertas/libertas_api/src/error.rs
2025-11-02 09:31:01 +01:00

44 lines
1.2 KiB
Rust

use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use libertas_core::error::CoreError;
use serde_json::json;
pub struct ApiError(CoreError);
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let (status, error_message) = match self.0 {
CoreError::Database(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Database error: {}", e),
),
CoreError::Validation(e) => (StatusCode::BAD_REQUEST, e),
CoreError::NotFound(res, id) => (
StatusCode::NOT_FOUND,
format!("{} with id {} not found", res, id),
),
CoreError::Duplicate(e) => (StatusCode::CONFLICT, e),
CoreError::Auth(e) => (StatusCode::UNAUTHORIZED, e),
_ => (
StatusCode::INTERNAL_SERVER_ERROR,
"An unknown error occurred".to_string(),
),
};
let body = Json(json!({ "error": error_message }));
(status, body).into_response()
}
}
impl<E> From<E> for ApiError
where
E: Into<CoreError>,
{
fn from(err: E) -> Self {
Self(err.into())
}
}