nexus_memory_web/
error.rs1use axum::{
4 http::StatusCode,
5 response::{IntoResponse, Response},
6 Json,
7};
8use serde_json::json;
9use thiserror::Error;
10
11pub type Result<T> = std::result::Result<T, WebError>;
13
14#[derive(Error, Debug)]
16pub enum WebError {
17 #[error("Storage error: {0}")]
18 Storage(String),
19
20 #[error("Orchestrator error: {0}")]
21 Orchestrator(String),
22
23 #[error("Invalid request: {0}")]
24 InvalidRequest(String),
25
26 #[error("Not found: {0}")]
27 NotFound(String),
28
29 #[error("Server error: {0}")]
30 ServerStart(String),
31
32 #[error("Serialization error: {0}")]
33 Serialization(#[from] serde_json::Error),
34
35 #[error("WebSocket error: {0}")]
36 WebSocket(String),
37
38 #[error("Configuration error: {0}")]
39 Config(String),
40}
41
42impl IntoResponse for WebError {
43 fn into_response(self) -> Response {
44 let (status, error_message) = match &self {
45 WebError::Storage(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
46 WebError::Orchestrator(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
47 WebError::InvalidRequest(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
48 WebError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()),
49 WebError::ServerStart(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
50 WebError::Serialization(_) => (StatusCode::BAD_REQUEST, "Invalid JSON".to_string()),
51 WebError::WebSocket(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
52 WebError::Config(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
53 };
54
55 let body = Json(json!({
56 "success": false,
57 "error": error_message,
58 }));
59
60 (status, body).into_response()
61 }
62}
63
64impl From<nexus_core::NexusError> for WebError {
65 fn from(err: nexus_core::NexusError) -> Self {
66 match err {
67 nexus_core::NexusError::Storage(msg) => WebError::Storage(msg),
68 nexus_core::NexusError::MemoryNotFound(id) => {
69 WebError::NotFound(format!("Memory not found: {}", id))
70 }
71 nexus_core::NexusError::NamespaceNotFound(name) => {
72 WebError::NotFound(format!("Namespace not found: {}", name))
73 }
74 nexus_core::NexusError::InvalidInput(msg) => WebError::InvalidRequest(msg),
75 nexus_core::NexusError::InvalidConfig(msg) => WebError::InvalidRequest(msg),
76 _ => WebError::Storage(err.to_string()),
77 }
78 }
79}
80
81impl From<nexus_orchestrator::OrchestratorError> for WebError {
82 fn from(err: nexus_orchestrator::OrchestratorError) -> Self {
83 WebError::Orchestrator(err.to_string())
84 }
85}
86
87impl From<sqlx::Error> for WebError {
88 fn from(err: sqlx::Error) -> Self {
89 WebError::Storage(err.to_string())
90 }
91}