openleadr_wire/problem.rs
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
use http::StatusCode;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct ProblemUri(String);
impl Default for ProblemUri {
fn default() -> Self {
Self("about:blank".to_string())
}
}
/// Reusable error response. From <https://opensource.zalando.com/problem/schema.yaml>.
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct Problem {
/// An absolute URI that identifies the problem type.
/// When dereferenced, it SHOULD provide human-readable documentation for the problem type
/// (e.g., using HTML).
#[serde(default)]
pub r#type: ProblemUri,
/// A short, summary of the problem type.
/// Written in english and readable for engineers
/// (usually not suited for non-technical stakeholders and not localized);
/// example: Service Unavailable.
pub title: Option<String>,
/// The HTTP status code generated by the origin server for this occurrence of the problem.
#[serde(with = "status_code_serialization")]
pub status: StatusCode,
/// A human-readable explanation specific to this occurrence of the problem.
pub detail: Option<String>,
/// An absolute URI that identifies the specific occurrence of the problem.
/// It may or may not yield further information if dereferenced.
pub instance: Option<String>,
}
mod status_code_serialization {
use super::*;
use serde::{de::Unexpected, Deserializer, Serializer};
pub fn serialize<S>(code: &StatusCode, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u16(code.as_u16())
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<StatusCode, D::Error>
where
D: Deserializer<'de>,
{
u16::deserialize(deserializer).and_then(|code| {
StatusCode::from_u16(code).map_err(|_| {
serde::de::Error::invalid_value(
Unexpected::Unsigned(code as u64),
&"Valid http status code",
)
})
})
}
}