Skip to main content

clightningrpc_common/
errors.rs

1// Rust JSON-RPC Library
2// Written in 2015 by
3//     Andrew Poelstra <apoelstra@wpsoftware.net>
4//
5// To the extent possible under law, the author(s) have dedicated all
6// copyright and related and neighboring rights to this software to
7// the public domain worldwide. This software is distributed without
8// any warranty.
9//
10// You should have received a copy of the CC0 Public Domain Dedication
11// along with this software.
12// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
13//
14
15/// Error module that contains all the error type
16/// used in the common crate.
17use std::io;
18use std::{error, fmt};
19
20use serde::{Deserialize, Serialize};
21use serde_json;
22
23/// A library error
24#[derive(Debug)]
25pub enum Error {
26    /// Json error
27    Json(serde_json::Error),
28    /// IO Error
29    Io(io::Error),
30    /// Error response
31    Rpc(RpcError),
32    /// Response has neither error nor result
33    NoErrorOrResult,
34    /// Response to a request did not have the expected nonce
35    NonceMismatch,
36    /// Response to a request had a jsonrpc field other than "2.0"
37    VersionMismatch,
38}
39
40impl From<serde_json::Error> for Error {
41    fn from(e: serde_json::Error) -> Error {
42        Error::Json(e)
43    }
44}
45
46impl From<io::Error> for Error {
47    fn from(e: io::Error) -> Error {
48        Error::Io(e)
49    }
50}
51
52impl From<RpcError> for Error {
53    fn from(e: RpcError) -> Error {
54        Error::Rpc(e)
55    }
56}
57
58impl fmt::Display for Error {
59    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60        match *self {
61            Error::Json(ref e) => write!(f, "JSON decode error: {e}"),
62            Error::Io(ref e) => write!(f, "IO error response: {e}"),
63            Error::Rpc(ref r) => write!(f, "RPC error response: {r:?}"),
64            Error::NoErrorOrResult => write!(f, "Malformed RPC response"),
65            Error::NonceMismatch => write!(f, "Nonce of response did not match nonce of request"),
66            Error::VersionMismatch => write!(f, "`jsonrpc` field set to non-\"2.0\""),
67        }
68    }
69}
70
71impl error::Error for Error {
72    fn cause(&self) -> Option<&dyn error::Error> {
73        match *self {
74            Error::Json(ref e) => Some(e),
75            _ => None,
76        }
77    }
78}
79
80#[allow(clippy::derive_partial_eq_without_eq)]
81#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
82/// A JSONRPCv2.0 spec compilant error object
83pub struct RpcError {
84    /// The integer identifier of the error
85    pub code: i32,
86    /// A string describing the error message
87    pub message: String,
88    /// Additional data specific to the error
89    pub data: Option<serde_json::Value>,
90}