use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use pib_service_inventory::ParseMeetingStateError;
use serde::{Deserialize, Serialize};
use snafu::{IntoError, Snafu};
#[derive(Debug, Snafu)]
pub enum Error {
Forbidden,
Inventory {
source: pib_service_inventory::Error,
},
Permissions {
source: pib_service_api_permissions::Error,
},
MeetingStateParse {
source: ParseMeetingStateError,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApiError {
pub message: String,
}
impl IntoResponse for Error {
fn into_response(self) -> Response {
let mut response = Json(ApiError {
message: format!("{self}"),
})
.into_response();
*response.status_mut() = if self.is_not_found() {
StatusCode::NOT_FOUND
} else if self.is_forbidden() {
StatusCode::FORBIDDEN
} else {
StatusCode::INTERNAL_SERVER_ERROR
};
response
}
}
impl Error {
pub fn is_not_found(&self) -> bool {
matches!(
self,
Error::Inventory {
source: pib_service_inventory::Error::NotFound
}
)
}
pub fn is_forbidden(&self) -> bool {
matches!(self, Error::Forbidden)
}
}
impl From<pib_service_inventory::Error> for Error {
fn from(source: pib_service_inventory::Error) -> Self {
InventorySnafu.into_error(source)
}
}
impl From<pib_service_api_permissions::Error> for Error {
fn from(source: pib_service_api_permissions::Error) -> Self {
PermissionsSnafu.into_error(source)
}
}
impl From<ParseMeetingStateError> for Error {
fn from(source: ParseMeetingStateError) -> Self {
MeetingStateParseSnafu.into_error(source)
}
}