Skip to main content

json_rpc/
error.rs

1//! Error types for the JSON-RPC implementation.
2//!
3//! This module defines internal errors that can occur during JSON-RPC processing,
4//! distinct from the JSON-RPC wire format errors defined in the `types` module.
5
6use std::io;
7
8/// Internal errors that can occur during JSON-RPC processing.
9///
10/// These are implementation-level errors, separate from the JSON-RPC protocol
11/// error objects that are sent over the wire (defined in `types::Error`).
12#[derive(Debug, thiserror::Error)]
13pub enum Error {
14    /// Protocol-level error, such as invalid method or parameters.
15    #[error("Protocol error: {0}")]
16    ProtocolError(String),
17
18    /// JSON-RPC error with specific code and message.
19    #[error("JSON-RPC error: code={code}, message={message}")]
20    RpcError { code: i32, message: String },
21
22    /// Transport I/O error.
23    #[error("Transport error: {0}")]
24    TransportError(#[from] io::Error),
25
26    /// JSON parsing error.
27    #[error("Protocol error: {0}")]
28    ParseError(#[from] serde_json::Error),
29
30    /// Invalid JSON-RPC request error.
31    #[error("Invalid Request: {0}")]
32    InvalidRequest(String),
33
34    /// Operation was cancelled.
35    #[error("Operation was cancelled")]
36    Cancelled,
37}
38
39impl Error {
40    /// Create a new protocol error.
41    pub fn protocol(message: impl Into<String>) -> Self {
42        Self::ProtocolError(message.into())
43    }
44
45    /// Create a new transport error.
46    pub fn transport(error: impl Into<io::Error>) -> Self {
47        Self::TransportError(error.into())
48    }
49
50    /// Create a new JSON-RPC error with a specific code and message.
51    pub fn rpc(code: i32, message: impl Into<String>) -> Self {
52        Self::RpcError {
53            code,
54            message: message.into(),
55        }
56    }
57
58    /// Create a new Invalid Request error.
59    pub fn invalid_request(message: impl Into<String>) -> Self {
60        Self::InvalidRequest(message.into())
61    }
62}