1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use crate::ProblemDetails;

/// ProblemDetails that is encoded to JSON when
/// used with web framework integrations.
///
/// # Example
///
/// ```rust
/// use http::StatusCode;
/// use problem_details::{JsonProblemDetails, ProblemDetails};
///
/// async fn handler() -> JsonProblemDetails {
///     ProblemDetails::from_status_code(StatusCode::IM_A_TEAPOT)
///         .with_detail("short and stout")
///         .into()
/// }
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct JsonProblemDetails<Ext = ()>(pub(crate) ProblemDetails<Ext>);

impl<Ext> JsonProblemDetails<Ext> {
    /// The HTTP content type for a json problem details.
    pub const CONTENT_TYPE: &'static str = "application/problem+json";
}

impl<Ext> JsonProblemDetails<Ext>
where
    Ext: serde::Serialize,
{
    /// Write this problem details to an JSON string suitable for a response body.
    pub fn to_body_string(&self) -> Result<String, JsonError> {
        serde_json::to_string(&self.0).map_err(|e| JsonError::Serialization(e))
    }
}

impl<Ext> From<ProblemDetails<Ext>> for JsonProblemDetails<Ext> {
    fn from(value: ProblemDetails<Ext>) -> Self {
        Self(value)
    }
}

impl<Ext> From<JsonProblemDetails<Ext>> for ProblemDetails<Ext> {
    fn from(value: JsonProblemDetails<Ext>) -> Self {
        value.0
    }
}
impl<Ext> std::fmt::Display for JsonProblemDetails<Ext> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl<Ext> std::error::Error for JsonProblemDetails<Ext> where Ext: std::fmt::Debug {}

#[derive(Debug)]
pub enum JsonError {
    Serialization(serde_json::Error),
}

impl std::fmt::Display for JsonError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Could not write body: {}",
            match self {
                Self::Serialization(err) => err,
            }
        )
    }
}

impl std::error::Error for JsonError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Serialization(err) => Some(err),
        }
    }
}