use axum::Json; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use serde_json::json; /// Fehler im OpenAI-Format: `{"error": {"message", "type", "param", "code"}}`. #[derive(Debug)] pub struct ApiError { status: StatusCode, kind: &'static str, code: &'static str, message: String, } impl ApiError { pub fn new( status: StatusCode, kind: &'static str, code: &'static str, message: impl Into, ) -> Self { Self { status, kind, code, message: message.into(), } } pub fn status(&self) -> StatusCode { self.status } pub fn invalid_key() -> Self { Self::new( StatusCode::UNAUTHORIZED, "invalid_request_error", "invalid_api_key", "Fehlender oder ungültiger API-Key. Erwartet wird der Header \"Authorization: Bearer \".", ) } pub fn model_not_found(model: &str) -> Self { Self::new( StatusCode::NOT_FOUND, "invalid_request_error", "model_not_found", format!( "Das Modell \"{model}\" existiert nicht oder ist für diesen Key nicht freigegeben." ), ) } pub fn bad_request(message: impl Into) -> Self { Self::new( StatusCode::BAD_REQUEST, "invalid_request_error", "invalid_request", message, ) } pub fn priority_not_permitted(requested: &str, max: &str) -> Self { Self::new( StatusCode::FORBIDDEN, "permission_error", "priority_not_permitted", format!( "Die Priorität \"{requested}\" ist für diesen Key nicht erlaubt (höchstens \"{max}\")." ), ) } pub fn engine_unavailable() -> Self { Self::new( StatusCode::SERVICE_UNAVAILABLE, "server_error", "engine_unavailable", "Das Modell konnte nicht gestartet werden. Details stehen im Log des Gateways.", ) } pub fn upstream() -> Self { Self::new( StatusCode::BAD_GATEWAY, "server_error", "upstream_error", "Die Engine hat nicht geantwortet.", ) } pub fn internal() -> Self { Self::new( StatusCode::INTERNAL_SERVER_ERROR, "server_error", "internal_error", "Interner Fehler. Details stehen im Log des Gateways.", ) } } impl IntoResponse for ApiError { fn into_response(self) -> Response { let body = json!({ "error": { "message": self.message, "type": self.kind, "param": null, "code": self.code, } }); (self.status, Json(body)).into_response() } }