File size: 1,529 Bytes
4f704aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use thiserror::Error;

use crate::types::anthropic::{Error as AnthropicError, InnerError};

#[derive(Error, Debug)]
pub enum AppError {
    #[error("Request error: {0}")]
    RequestError(String),

    #[error("Upstream error: {0} - {1}")]
    UpstreamError(u16, String),

    #[error("Invalid request: {0}")]
    InvalidRequest(String),

    #[allow(dead_code)]
    #[error("Internal error: {0}")]
    InternalError(String),
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, error_type, message) = match &self {
            AppError::RequestError(msg) => (StatusCode::BAD_GATEWAY, "api_error", msg.clone()),
            AppError::UpstreamError(code, msg) => {
                let status = StatusCode::from_u16(*code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
                (status, "api_error", msg.clone())
            }
            AppError::InvalidRequest(msg) => {
                (StatusCode::BAD_REQUEST, "invalid_request_error", msg.clone())
            }
            AppError::InternalError(msg) => {
                (StatusCode::INTERNAL_SERVER_ERROR, "api_error", msg.clone())
            }
        };

        let error = AnthropicError {
            content_type: "error".to_string(),
            error: InnerError {
                error_type: error_type.to_string(),
                message,
            },
        };

        (status, Json(error)).into_response()
    }
}