//! Application error type shared by every surface. //! //! Sources return `AppError`; REST renders it through [`IntoResponse`], MCP //! through `From for rmcp::ErrorData`. use axum::http::{header, HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::Json; #[derive(Debug, Clone, thiserror::Error)] pub enum AppError { /// Unknown unit, container, route target. #[error("not found: {0}")] NotFound(String), /// Invalid input (bad unit name, out-of-range limit, bad priority). #[error("bad request: {0}")] BadRequest(String), /// Missing, malformed, unknown or revoked bearer token. #[error("unauthorized: {0}")] Unauthorized(String), /// A backend (D-Bus, journald, Docker socket, DB) is absent or denied. #[error("unavailable: {0}")] Unavailable(String), /// Anything else. Details are logged, not necessarily exposed. #[error("internal error: {0}")] Internal(String), } impl AppError { /// Stable machine-readable code used in REST bodies and MCP error data. pub fn code(&self) -> &'static str { match self { Self::NotFound(_) => "not_found", Self::BadRequest(_) => "bad_request", Self::Unauthorized(_) => "unauthorized", Self::Unavailable(_) => "unavailable", Self::Internal(_) => "internal", } } pub fn status(&self) -> StatusCode { match self { Self::NotFound(_) => StatusCode::NOT_FOUND, Self::BadRequest(_) => StatusCode::BAD_REQUEST, Self::Unauthorized(_) => StatusCode::UNAUTHORIZED, Self::Unavailable(_) => StatusCode::SERVICE_UNAVAILABLE, Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, } } /// The bare message without the variant prefix. pub fn message(&self) -> &str { match self { Self::NotFound(m) | Self::BadRequest(m) | Self::Unauthorized(m) | Self::Unavailable(m) | Self::Internal(m) => m, } } } /// REST error body: `{"error": {"code": "...", "message": "..."}}`. pub fn error_response(status: StatusCode, code: &str, message: &str) -> Response { let body = serde_json::json!({"error": {"code": code, "message": message}}); (status, Json(body)).into_response() } impl IntoResponse for AppError { fn into_response(self) -> Response { let mut resp = error_response(self.status(), self.code(), self.message()); if matches!(self, AppError::Unauthorized(_)) { resp.headers_mut() .insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); } resp } } impl From for rmcp::ErrorData { fn from(err: AppError) -> Self { let data = Some(serde_json::json!({ "code": err.code() })); let msg = err.message().to_owned(); match err { AppError::NotFound(_) => rmcp::ErrorData::resource_not_found(msg, data), AppError::BadRequest(_) => rmcp::ErrorData::invalid_params(msg, data), AppError::Unauthorized(_) => rmcp::ErrorData::invalid_request(msg, data), AppError::Unavailable(_) | AppError::Internal(_) => { rmcp::ErrorData::internal_error(msg, data) } } } } impl From for AppError { fn from(err: sqlx::Error) -> Self { AppError::Internal(format!("database: {err}")) } } #[cfg(test)] mod tests { use super::*; #[test] fn status_and_code() { let e = AppError::NotFound("x".into()); assert_eq!(e.status(), StatusCode::NOT_FOUND); assert_eq!(e.code(), "not_found"); let r = AppError::Unauthorized("no".into()).into_response(); assert_eq!(r.status(), StatusCode::UNAUTHORIZED); assert!(r.headers().contains_key(header::WWW_AUTHENTICATE)); } #[test] fn mcp_mapping() { let e: rmcp::ErrorData = AppError::BadRequest("bad".into()).into(); assert_eq!(e.message, "bad"); } }