use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use std::fmt;
#[derive(Debug)]
pub enum AppError {
Internal,
BadRequest(String),
NotFound,
Conflict(String),
Locked(String),
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Internal => write!(f, "internal server error"),
Self::BadRequest(msg) => write!(f, "bad request: {msg}"),
Self::NotFound => write!(f, "not found"),
Self::Conflict(msg) => write!(f, "conflict: {msg}"),
Self::Locked(msg) => write!(f, "locked: {msg}"),
}
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = match &self {
Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
Self::BadRequest(_) => StatusCode::BAD_REQUEST,
Self::NotFound => StatusCode::NOT_FOUND,
Self::Conflict(_) => StatusCode::CONFLICT,
Self::Locked(_) => StatusCode::LOCKED,
};
(
status,
Json(serde_json::json!({ "error": self.to_string() })),
)
.into_response()
}
}
#[cfg(test)]
#[path = "error_tests.rs"]
mod error_tests;