use actix_web::http::StatusCode;
use serde::{Deserialize, Serialize};
use crate::db::NotFound;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApiError {
ConfigNamespace,
NotFound(NotFound),
EmptyValue,
InvalidTimestamp(i64),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Message {
pub message: String,
}
impl Message {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
}
impl std::fmt::Display for ApiError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ApiError::ConfigNamespace => {
write!(f, "No access to _config namespace from outside!")
}
ApiError::NotFound(nf) => write!(f, "{}", nf.error),
ApiError::EmptyValue => write!(f, "Refusing to write an empty value."),
ApiError::InvalidTimestamp(ts) => write!(f, "Timestamp out of range: {ts}"),
}
}
}
impl std::error::Error for ApiError {}
impl ApiError {
pub fn status(&self) -> StatusCode {
match self {
ApiError::ConfigNamespace => StatusCode::FORBIDDEN,
ApiError::NotFound(_) => StatusCode::NOT_FOUND,
ApiError::EmptyValue | ApiError::InvalidTimestamp(_) => StatusCode::BAD_REQUEST,
}
}
pub fn body(&self) -> serde_json::Value {
match self {
ApiError::NotFound(nf) => serde_json::json!(nf),
ApiError::ConfigNamespace => {
serde_json::json!(Message::new("No access to _config namespace from outside!"))
}
ApiError::EmptyValue => {
serde_json::json!(Message::new("Refusing to write an empty value."))
}
ApiError::InvalidTimestamp(ts) => {
serde_json::json!(Message::new(format!("Timestamp out of range: {ts}")))
}
}
}
}