lampo_jsonrpc/
errors.rs

1use std::io;
2use std::{error, fmt};
3
4use serde::{Deserialize, Serialize};
5use serde_json;
6
7/// A library error
8#[derive(Debug)]
9pub enum Error {
10    /// Json error
11    Json(serde_json::Error),
12    /// IO Error
13    Io(io::Error),
14    /// Error response
15    Rpc(RpcError),
16    /// Response has neither error nor result
17    NoErrorOrResult,
18    /// Response to a request did not have the expected nonce
19    NonceMismatch,
20    /// Response to a request had a jsonrpc field other than "2.0"
21    VersionMismatch,
22}
23
24impl From<serde_json::Error> for Error {
25    fn from(e: serde_json::Error) -> Error {
26        Error::Json(e)
27    }
28}
29
30impl From<io::Error> for Error {
31    fn from(e: io::Error) -> Error {
32        Error::Io(e)
33    }
34}
35
36impl From<RpcError> for Error {
37    fn from(e: RpcError) -> Error {
38        Error::Rpc(e)
39    }
40}
41
42impl fmt::Display for Error {
43    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44        match *self {
45            Error::Json(ref e) => write!(f, "JSON decode error: {e}"),
46            Error::Io(ref e) => write!(f, "IO error response: {e}"),
47            Error::Rpc(ref r) => write!(f, "RPC error response: {r:?}"),
48            Error::NoErrorOrResult => write!(f, "Malformed RPC response"),
49            Error::NonceMismatch => write!(f, "Nonce of response did not match nonce of request"),
50            Error::VersionMismatch => write!(f, "`jsonrpc` field set to non-\"2.0\""),
51        }
52    }
53}
54
55impl error::Error for Error {
56    fn cause(&self) -> Option<&dyn error::Error> {
57        match *self {
58            Error::Json(ref e) => Some(e),
59            _ => None,
60        }
61    }
62}
63
64#[allow(clippy::derive_partial_eq_without_eq)]
65#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
66/// A JSONRPCv2.0 spec compilant error object
67pub struct RpcError {
68    /// The integer identifier of the error
69    pub code: i32,
70    /// A string describing the error message
71    pub message: String,
72    /// Additional data specific to the error
73    pub data: Option<serde_json::Value>,
74}
75
76impl From<Error> for RpcError {
77    fn from(value: Error) -> Self {
78        match value {
79            Error::Rpc(rpc) => return rpc.clone(),
80            _ => RpcError {
81                code: -1,
82                message: format!("{value}"),
83                data: None,
84            },
85        }
86    }
87}