Skip to main content

alux_jsonrpc_direct/
error.rs

1use alux_jsonrpc::RpcErrorAlg;
2use core::error::Error;
3use core::fmt::{self, Display};
4use derive_new::new as New;
5use serde::Serialize;
6
7/// The code a malformed JSON document carries.
8pub const PARSE_ERROR: i32 = -32700;
9/// The code a document that is not a JSON-RPC request carries.
10pub const INVALID_REQUEST: i32 = -32600;
11/// The code an unknown method name carries.
12pub const METHOD_NOT_FOUND: i32 = -32601;
13/// The code a parameter the method cannot read carries.
14pub const INVALID_PARAMS: i32 = -32602;
15/// The code a failure of the interpretation itself carries.
16pub const INTERNAL_ERROR: i32 = -32603;
17
18/// What a JSON-RPC response states in its `error` member.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, New)]
20pub struct RpcError {
21    /// The code this failure carries.
22    pub code: i32,
23    /// The message this failure states.
24    #[new(into)]
25    pub message: String,
26}
27
28impl RpcError {
29    /// Reads the error a domain failure denotes.
30    pub fn denoted<Failure>(failure: &Failure) -> Self
31    where
32        Failure: RpcErrorAlg,
33    {
34        Self { code: failure.rpc_code(), message: failure.rpc_message() }
35    }
36
37    /// States that a document is not JSON.
38    pub fn parse_error() -> Self {
39        Self::new(PARSE_ERROR, "invalid JSON")
40    }
41
42    /// States that a document is JSON but not a JSON-RPC request.
43    pub fn invalid_request() -> Self {
44        Self::new(INVALID_REQUEST, "invalid request")
45    }
46
47    /// States that no method answers to a name.
48    pub fn method_not_found(method: &str) -> Self {
49        Self::new(METHOD_NOT_FOUND, format!("method `{method}` not found"))
50    }
51}
52
53impl Display for RpcError {
54    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55        write!(formatter, "{} ({})", self.message, self.code)
56    }
57}
58
59impl Error for RpcError {}
60
61/// A domain can answer with this error directly, stating its own code and message.
62impl RpcErrorAlg for RpcError {
63    fn rpc_code(&self) -> i32 {
64        self.code
65    }
66
67    fn rpc_message(&self) -> String {
68        self.message.clone()
69    }
70}