Debian Codegraph @

src/response/error.rs

raw
1 //! RFC 9083 Error
2 use std::collections::HashSet;
3
4 use {
5 crate::prelude::Extension,
6 serde::{Deserialize, Serialize},
7 };
8
9 use crate::media_types::RDAP_MEDIA_TYPE;
10 use crate::prelude::ContentExtensions;
11
12 use super::{
13 Common, CommonFields, ToResponse,
14 types::{Link, Notice, NoticeOrRemark},
15 };
16
17 use super::lenient::{Numberish, Stringish, VectorStringish};
18
19 /// Represents an error response from an RDAP server.
20 ///
21 /// This structure represents the JSON returned by an RDAP server
22 /// describing an error.
23 /// See [RFC 9083, Section 6](https://datatracker.ietf.org/doc/html/rfc9083#name-error-response-body).
24 ///
25 /// Do not confuse this with [crate::response::RdapResponseError].
26 ///
27 /// Use the builders to create one:
28 /// ```rust
29 /// use icann_rdap_common::prelude::*;
30 ///
31 /// let e = Rfc9083Error::response_obj()
32 /// .error_code(500)
33 /// .build();
34 /// ```
35 ///
36 /// Use the getter functions to access information.
37 /// See [CommonFields] for common getter functions.
38 /// ```rust
39 /// # use icann_rdap_common::prelude::*;
40 /// # let e = Rfc9083Error::response_obj()
41 /// # .error_code(500)
42 /// # .build();
43 /// let error_code = e.error_code();
44 /// ```
45 #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
46 pub struct Rfc9083Error {
47 #[serde(flatten)]
48 pub common: Common,
49
50 #[serde(rename = "errorCode")]
51 pub error_code: Numberish<u16>,
52
53 #[serde(skip_serializing_if = "Option::is_none")]
54 pub title: Option<Stringish>,
55
56 #[serde(skip_serializing_if = "Option::is_none")]
57 pub description: Option<VectorStringish>,
58 }
59
60 #[buildstructor::buildstructor]
61 impl Rfc9083Error {
62 /// Creates a new RFC 9083 Error for a specific HTTP error code.
63 ///
64 /// Use this builder to create a generic error:
65 /// ```rust
66 /// use icann_rdap_common::prelude::*;
67 ///
68 /// let e = Rfc9083Error::response_obj()
69 /// .error_code(500) //required
70 /// .build();
71 /// ```
72 #[builder(entry = "response_obj", visibility = "pub")]
73 fn new_response_obj(
74 error_code: u16,
75 notices: Vec<Notice>,
76 title: Option<String>,
77 description: Vec<String>,
78 extensions: Vec<Extension>,
79 ) -> Self {
80 let notices = (!notices.is_empty()).then_some(notices);
81 Self {
82 common: Common::level0()
83 .extensions(extensions)
84 .and_notices(notices)
85 .build(),
86 error_code: Numberish::from(error_code),
87 title: title.map(Stringish::from),
88 description: Some(VectorStringish::from(description)),
89 }
90 }
91
92 /// Creates an RFC 9083 error for an HTTP redirect.
93 #[builder(entry = "redirect", visibility = "pub")]
94 fn new_redirect(url: String, extensions: Vec<Extension>) -> Self {
95 let links = vec![
96 Link::builder()
97 .href(&url)
98 .value(&url)
99 .media_type(RDAP_MEDIA_TYPE)
100 .rel("related")
101 .build(),
102 ];
103 let notices = vec![Notice(NoticeOrRemark::builder().links(links).build())];
104 Self {
105 common: Common::level0()
106 .extensions(extensions)
107 .notices(notices)
108 .build(),
109 error_code: Numberish::from(307u16),
110 title: None,
111 description: None,
112 }
113 }
114
115 /// Get the errorCode.
116 pub fn error_code(&self) -> u16 {
117 self.error_code.as_u16().unwrap_or(0)
118 }
119
120 /// Get the title.
121 pub fn title(&self) -> Option<&str> {
122 self.title.as_ref().map(|s| s.as_ref())
123 }
124
125 /// Get the description.
126 pub fn description(&self) -> &[String] {
127 self.description.as_ref().map_or(&[], |v| v.vec())
128 }
129
130 /// True if the error is an HTTP redirect.
131 pub fn is_redirect(&self) -> bool {
132 let code = self.error_code.as_u16().unwrap_or(0);
133 code > 299 && code < 400
134 }
135 }
136
137 impl CommonFields for Rfc9083Error {
138 fn common(&self) -> &Common {
139 &self.common
140 }
141 }
142
143 impl ToResponse for Rfc9083Error {
144 fn to_response(self) -> super::RdapResponse {
145 super::RdapResponse::ErrorResponse(Box::new(self))
146 }
147 }
148
149 impl ContentExtensions for Rfc9083Error {
150 fn content_extensions(&self) -> std::collections::HashSet<super::ExtensionId> {
151 let mut exts = HashSet::new();
152 exts.extend(self.common().content_extensions());
153 exts
154 }
155 }
156
157 #[cfg(test)]
158 mod tests {
159 use super::Rfc9083Error;
160
161 #[test]
162 fn error_code_301_is_redirect() {
163 // GIVEN
164 let e = Rfc9083Error::redirect().url("https://foo.example").build();
165
166 // WHEN
167 let actual = e.is_redirect();
168
169 // THEN
170 assert!(actual);
171 }
172
173 #[test]
174 fn error_code_404_is_not_redirect() {
175 // GIVEN
176 let e = Rfc9083Error::response_obj().error_code(404).build();
177
178 // WHEN
179 let actual = e.is_redirect();
180
181 // THEN
182 assert!(!actual);
183 }
184
185 #[test]
186 fn string_error_code_deserialize() {
187 // GIVEN
188 let json = r#"{"errorCode": "404"}"#;
189
190 // WHEN
191 let e: Rfc9083Error = serde_json::from_str(json).unwrap();
192
193 // THEN
194 assert_eq!(e.error_code(), 404);
195 assert!(e.error_code.is_string());
196 }
197
198 #[test]
199 fn number_error_code_deserialize() {
200 // GIVEN
201 let json = r#"{"errorCode": 404}"#;
202
203 // WHEN
204 let e: Rfc9083Error = serde_json::from_str(json).unwrap();
205
206 // THEN
207 assert_eq!(e.error_code(), 404);
208 assert!(!e.error_code.is_string());
209 }
210
211 #[test]
212 fn string_description_deserialize() {
213 // GIVEN
214 let json = r#"{"errorCode": 404, "description": "Not found"}"#;
215
216 // WHEN
217 let e: Rfc9083Error = serde_json::from_str(json).unwrap();
218
219 // THEN
220 assert_eq!(e.description(), &["Not found".to_string()]);
221 assert!(e.description.as_ref().unwrap().is_string());
222 }
223
224 #[test]
225 fn array_description_deserialize() {
226 // GIVEN
227 let json = r#"{"errorCode": 404, "description": ["Not found", "Resource missing"]}"#;
228
229 // WHEN
230 let e: Rfc9083Error = serde_json::from_str(json).unwrap();
231
232 // THEN
233 assert_eq!(
234 e.description(),
235 &["Not found".to_string(), "Resource missing".to_string()]
236 );
237 assert!(!e.description.as_ref().unwrap().is_string());
238 }
239
240 #[test]
241 fn number_title_deserialize() {
242 // GIVEN
243 let json = r#"{"errorCode": 404, "title": 123}"#;
244
245 // WHEN
246 let e: Rfc9083Error = serde_json::from_str(json).unwrap();
247
248 // THEN
249 assert_eq!(e.title(), Some("123"));
250 assert!(e.title.as_ref().unwrap().is_number());
251 }
252
253 #[test]
254 fn bool_title_deserialize() {
255 // GIVEN
256 let json = r#"{"errorCode": 404, "title": true}"#;
257
258 // WHEN
259 let e: Rfc9083Error = serde_json::from_str(json).unwrap();
260
261 // THEN
262 assert_eq!(e.title(), Some("true"));
263 assert!(e.title.as_ref().unwrap().is_bool());
264 }
265
266 #[test]
267 fn string_title_deserialize() {
268 // GIVEN
269 let json = r#"{"errorCode": 404, "title": "Not Found"}"#;
270
271 // WHEN
272 let e: Rfc9083Error = serde_json::from_str(json).unwrap();
273
274 // THEN
275 assert_eq!(e.title(), Some("Not Found"));
276 assert!(!e.title.as_ref().unwrap().is_number());
277 assert!(!e.title.as_ref().unwrap().is_bool());
278 }
279 }