thin_jsonrpc_client/
response.rs

1use std::sync::Arc;
2use crate::raw_response::RawResponse;
3
4/// A JSON-RPC response.
5#[derive(Debug, Clone)]
6pub struct Response(pub(crate) Arc<RawResponse<'static>>);
7
8/// An error returned from trying to deserialize the response.
9#[derive(derive_more::Display, Debug)]
10pub enum ResponseError {
11    /// A JSON-RPC error object was returned. and so the "ok"
12    /// value could not be deserialized.
13    #[display(fmt = "An ok or error value was expected, and the other was received.")]
14    WrongResponse,
15    /// An error deserializing some received JSON into the expected
16    /// JSON-RPC format.
17    Deserialize(serde_json::Error),
18}
19
20impl std::error::Error for ResponseError {
21    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
22        match self {
23            ResponseError::WrongResponse => None,
24            ResponseError::Deserialize(err) => Some(err)
25        }
26    }
27}
28
29impl Response {
30    /// Hand back the raw response from the server.
31    pub fn raw(&self) -> &RawResponse<'static> {
32        &self.0
33    }
34
35    /// Deserialize an "ok" response to the requested type.
36    pub fn ok_into<R: serde::de::DeserializeOwned>(&self) -> Result<R, ResponseError> {
37        let res = match self.raw() {
38            RawResponse::Ok(res) => res,
39            RawResponse::Error(_) => return Err(ResponseError::WrongResponse)
40        };
41
42        serde_json::from_str(res.result.get()).map_err(ResponseError::Deserialize)
43    }
44
45    /// Deserialize an "error" response to the requested type.
46    pub fn error_into<Data: serde::de::DeserializeOwned>(&self) -> Result<ErrorObject<Data>, ResponseError> {
47        let err = match self.raw() {
48            RawResponse::Error(err) => err,
49            RawResponse::Ok(_) => return Err(ResponseError::WrongResponse)
50        };
51
52        let data = err.error.data.as_ref().map(|d| d.get()).unwrap_or("null");
53        let data = serde_json::from_str(data).map_err(ResponseError::Deserialize)?;
54
55        Ok(ErrorObject {
56            code: err.error.code,
57            message: err.error.message.as_ref().to_owned(),
58            data
59        })
60    }
61}
62
63/// The deserialized error object returned from [`Response::err_into()`].
64pub struct ErrorObject<Data> {
65    pub code: i32,
66    pub message: String,
67    pub data: Data
68}