inth_oauth2_async/client/
response.rs

1//! Response parsing.
2
3use std::error::Error;
4use std::fmt;
5
6use serde_json::Value;
7
8/// Response parsing.
9pub trait FromResponse: Sized {
10    /// Parse a JSON response.
11    fn from_response(json: &Value) -> Result<Self, ParseError>;
12
13    /// Parse a JSON response, inheriting missing values from the previous instance.
14    ///
15    /// Necessary for parsing refresh token responses where the absence of a new refresh token
16    /// implies that the previous refresh token is still valid.
17    #[allow(unused_variables)]
18    fn from_response_inherit(json: &Value, prev: &Self) -> Result<Self, ParseError> {
19        FromResponse::from_response(json)
20    }
21}
22
23/// Response parse errors.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum ParseError {
26    /// Expected response to be of type.
27    ExpectedType(&'static str),
28
29    /// Expected field to be of type.
30    ExpectedFieldType(&'static str, &'static str),
31
32    /// Expected field to equal value.
33    ExpectedFieldValue(&'static str, &'static str),
34
35    /// Expected field to not be present.
36    UnexpectedField(&'static str),
37}
38
39impl fmt::Display for ParseError {
40    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
41        match *self {
42            ParseError::ExpectedType(t) =>
43                write!(f, "Expected response of type {}", t),
44            ParseError::ExpectedFieldType(k, t) =>
45                write!(f, "Expected field {} of type {}", k, t),
46            ParseError::ExpectedFieldValue(k, v) =>
47                write!(f, "Expected field {} to equal {}", k, v),
48            ParseError::UnexpectedField(k) =>
49                write!(f, "Unexpected field {}", k),
50        }
51    }
52}
53
54impl Error for ParseError {
55    fn description(&self) -> &str { "response parse error" }
56}