use aonyx_core::AonyxError;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde_json::json;
pub type ApiResult<T> = std::result::Result<T, ApiError>;
#[derive(Debug, thiserror::Error)]
pub enum ApiError {
#[error("{0}")]
Unauthorized(String),
#[error("{0}")]
Forbidden(String),
#[error("{0}")]
BadRequest(String),
#[error("{0}")]
NotFound(String),
#[error("{0}")]
Internal(String),
}
impl ApiError {
fn parts(&self) -> (StatusCode, &'static str) {
match self {
ApiError::Unauthorized(_) => (StatusCode::UNAUTHORIZED, "unauthorized"),
ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, "forbidden"),
ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, "bad_request"),
ApiError::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"),
ApiError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal"),
}
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let (status, ty) = self.parts();
let body = Json(json!({ "error": { "type": ty, "message": self.to_string() } }));
(status, body).into_response()
}
}
impl From<AonyxError> for ApiError {
fn from(e: AonyxError) -> Self {
match e {
AonyxError::Config(m) => ApiError::BadRequest(m),
AonyxError::ApprovalRejected(m) => ApiError::Forbidden(m),
other => ApiError::Internal(other.to_string()),
}
}
}