Skip to main content

hindsight/server/
error.rs

1//! API error types and axum response conversion
2
3use axum::{
4    http::StatusCode,
5    response::{IntoResponse, Response},
6    Json,
7};
8use serde_json::json;
9use thiserror::Error;
10
11#[derive(Debug, Error)]
12pub enum ApiError {
13    #[error("Not found: {0}")]
14    NotFound(String),
15
16    #[error("Internal error: {0}")]
17    Internal(String),
18}
19
20impl From<crate::error::HindsightError> for ApiError {
21    fn from(e: crate::error::HindsightError) -> Self {
22        ApiError::Internal(e.to_string())
23    }
24}
25
26impl From<anyhow::Error> for ApiError {
27    fn from(e: anyhow::Error) -> Self {
28        ApiError::Internal(e.to_string())
29    }
30}
31
32impl IntoResponse for ApiError {
33    fn into_response(self) -> Response {
34        let (status, message) = match &self {
35            ApiError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()),
36            ApiError::Internal(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
37        };
38        (status, Json(json!({ "error": message }))).into_response()
39    }
40}