Skip to main content

routa_core/rpc/
error.rs

1//! RPC error type that bridges `ServerError` to JSON-RPC errors.
2
3use super::types;
4use crate::error::ServerError;
5
6/// Unified RPC error that can be converted to a JSON-RPC error response.
7#[derive(Debug, thiserror::Error)]
8pub enum RpcError {
9    #[error("Not found: {0}")]
10    NotFound(String),
11
12    #[error("Bad request: {0}")]
13    BadRequest(String),
14
15    #[error("Internal error: {0}")]
16    Internal(String),
17
18    #[error("Invalid params: {0}")]
19    InvalidParams(String),
20
21    #[error("Method not found: {0}")]
22    MethodNotFound(String),
23}
24
25impl RpcError {
26    /// Convert to a JSON-RPC error code.
27    pub fn code(&self) -> i64 {
28        match self {
29            RpcError::NotFound(_) => types::NOT_FOUND,
30            RpcError::BadRequest(_) => types::BAD_REQUEST,
31            RpcError::Internal(_) => types::INTERNAL_ERROR,
32            RpcError::InvalidParams(_) => types::INVALID_PARAMS,
33            RpcError::MethodNotFound(_) => types::METHOD_NOT_FOUND,
34        }
35    }
36
37    /// Convert to a JSON-RPC error response.
38    pub fn to_response(&self, id: Option<serde_json::Value>) -> types::JsonRpcResponse {
39        types::JsonRpcResponse::error(id, self.code(), self.to_string())
40    }
41}
42
43impl From<ServerError> for RpcError {
44    fn from(err: ServerError) -> Self {
45        match err {
46            ServerError::NotFound(msg) => RpcError::NotFound(msg),
47            ServerError::BadRequest(msg) => RpcError::BadRequest(msg),
48            ServerError::Conflict(msg) => RpcError::BadRequest(msg),
49            ServerError::Database(msg) => RpcError::Internal(msg),
50            ServerError::Internal(msg) => RpcError::Internal(msg),
51            ServerError::NotImplemented(msg) => RpcError::Internal(msg),
52        }
53    }
54}