1use std::fmt;
21
22use http::HeaderMap;
23use serde::{Deserialize, Deserializer};
24use serde_json::Value;
25
26#[derive(Debug, Clone, Default, PartialEq, Eq)]
28pub struct ErrorItem {
29 pub reason: String,
31 pub message: String,
33}
34
35#[derive(Debug, Clone, Default)]
38pub struct ApiError {
39 pub code: u16,
41 pub message: String,
43 pub details: Vec<Value>,
45 pub body: String,
47 pub header: HeaderMap,
49 pub errors: Vec<ErrorItem>,
51}
52
53impl fmt::Display for ApiError {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 if self.errors.is_empty() && self.message.is_empty() {
57 return write!(
58 f,
59 "googleapi: got HTTP response code {} with body: {}",
60 self.code, self.body
61 );
62 }
63 let mut buf = format!("googleapi: Error {}: ", self.code);
64 buf.push_str(&self.message);
65 if !self.details.is_empty()
66 && let Ok(compact) = crate::to_go_json(&self.details)
67 {
68 buf.push_str("\nDetails:");
70 buf.push('\n');
71 buf.push_str(&go_json_indent(&compact));
72 buf.push('\n');
73 }
74 if self.errors.is_empty() {
75 return f.write_str(buf.trim());
76 }
77 if self.errors.len() == 1 && self.errors[0].message == self.message {
78 buf.push_str(", ");
79 buf.push_str(&self.errors[0].reason);
80 return f.write_str(&buf);
81 }
82 buf.push_str("\nMore details:\n");
83 for e in &self.errors {
84 buf.push_str(&format!("Reason: {}, Message: {}\n", e.reason, e.message));
85 }
86 f.write_str(&buf)
87 }
88}
89
90impl std::error::Error for ApiError {}
91
92fn go_json_indent(compact: &[u8]) -> String {
94 let text = String::from_utf8_lossy(compact);
95 let mut out = String::with_capacity(text.len() * 2);
96 let mut depth = 0usize;
97 let mut in_string = false;
98 let mut escaped = false;
99 let mut need_indent = false;
100 let newline = |out: &mut String, depth: usize| {
101 out.push('\n');
102 for _ in 0..depth {
103 out.push_str(" ");
104 }
105 };
106 for c in text.chars() {
107 if in_string {
108 out.push(c);
109 if escaped {
110 escaped = false;
111 } else if c == '\\' {
112 escaped = true;
113 } else if c == '"' {
114 in_string = false;
115 }
116 continue;
117 }
118 match c {
119 '{' | '[' => {
120 if need_indent {
121 newline(&mut out, depth);
122 }
123 out.push(c);
124 depth += 1;
125 need_indent = true;
126 }
127 '}' | ']' => {
128 depth = depth.saturating_sub(1);
129 if need_indent {
130 need_indent = false;
132 } else {
133 newline(&mut out, depth);
134 }
135 out.push(c);
136 }
137 ',' => {
138 out.push(c);
139 newline(&mut out, depth);
140 }
141 ':' => out.push_str(": "),
142 _ => {
143 if need_indent {
144 newline(&mut out, depth);
145 need_indent = false;
146 }
147 if c == '"' {
148 in_string = true;
149 }
150 out.push(c);
151 }
152 }
153 }
154 out
155}
156
157pub fn check_response(parts: &http::response::Parts, body: &[u8]) -> Result<(), Box<ApiError>> {
159 if parts.status.is_success() {
160 return Ok(());
161 }
162 Err(Box::new(api_error_from_response(parts, body)))
163}
164
165pub fn api_error_from_response(parts: &http::response::Parts, body: &[u8]) -> ApiError {
168 let status = parts.status.as_u16();
169 let mut err = ApiError {
170 code: status,
171 body: String::from_utf8_lossy(body).into_owned(),
172 header: parts.headers.clone(),
173 ..ApiError::default()
174 };
175 if let Some(reply) = error_reply_from_body(body) {
176 if reply.code != 0 {
177 err.code = u16::try_from(reply.code).unwrap_or(status);
180 }
181 err.message = reply.message;
182 err.details = reply.details;
183 err.errors = reply
185 .errors
186 .into_iter()
187 .map(|i| {
188 let i = i.unwrap_or_default();
189 ErrorItem {
190 reason: i.reason,
191 message: i.message,
192 }
193 })
194 .collect();
195 }
196 err
197}
198
199#[derive(Deserialize)]
200struct ErrorReply {
201 error: Option<ErrorReplyBody>,
202}
203
204#[derive(Deserialize)]
205struct ErrorReplyBody {
206 #[serde(default, deserialize_with = "nullable")]
207 code: i64,
208 #[serde(default, deserialize_with = "nullable")]
209 message: String,
210 #[serde(default, deserialize_with = "nullable")]
211 details: Vec<Value>,
212 #[serde(default, deserialize_with = "nullable")]
213 errors: Vec<Option<ErrorItemReply>>,
214}
215
216#[derive(Default, Deserialize)]
217#[serde(default)]
218struct ErrorItemReply {
219 #[serde(deserialize_with = "nullable")]
220 reason: String,
221 #[serde(deserialize_with = "nullable")]
222 message: String,
223}
224
225fn error_reply_from_body(body: &[u8]) -> Option<ErrorReplyBody> {
228 if body.first() == Some(&b'[') {
229 let mut replies: Vec<ErrorReply> = serde_json::from_slice(body).ok()?;
230 if replies.is_empty() {
231 return None;
232 }
233 return replies.swap_remove(0).error;
234 }
235 serde_json::from_slice::<ErrorReply>(body).ok()?.error
236}
237
238fn nullable<'de, D, T>(d: D) -> Result<T, D::Error>
240where
241 D: Deserializer<'de>,
242 T: Deserialize<'de> + Default,
243{
244 Ok(Option::<T>::deserialize(d)?.unwrap_or_default())
245}
246
247#[cfg(test)]
248mod tests {
249 #![allow(clippy::unwrap_used)]
250
251 use serde_json::json;
252
253 use super::*;
254
255 fn parts(status: u16) -> http::response::Parts {
256 let (mut parts, ()) = http::Response::new(()).into_parts();
257 parts.status = http::StatusCode::from_u16(status).unwrap();
258 parts
259 }
260
261 #[test]
262 fn display_is_gos_error_text() {
263 let no_message = ApiError {
264 code: 502,
265 body: "bad gateway".into(),
266 ..ApiError::default()
267 };
268 assert_eq!(
269 no_message.to_string(),
270 "googleapi: got HTTP response code 502 with body: bad gateway"
271 );
272 let one_item = ApiError {
273 code: 404,
274 message: "nf".into(),
275 errors: vec![ErrorItem {
276 reason: "notFound".into(),
277 message: "nf".into(),
278 }],
279 ..ApiError::default()
280 };
281 assert_eq!(one_item.to_string(), "googleapi: Error 404: nf, notFound");
282 let many = ApiError {
283 code: 400,
284 message: "bad".into(),
285 errors: vec![
286 ErrorItem {
287 reason: "invalid".into(),
288 message: "a".into(),
289 },
290 ErrorItem::default(),
291 ],
292 ..ApiError::default()
293 };
294 assert_eq!(
295 many.to_string(),
296 "googleapi: Error 400: bad\nMore details:\nReason: invalid, Message: a\nReason: , \
297 Message: \n"
298 );
299 let details = ApiError {
300 code: 400,
301 message: "bad".into(),
302 details: vec![json!({"@type": "t<x>", "empty": {}, "list": [1, 2], "none": []})],
303 ..ApiError::default()
304 };
305 assert_eq!(
306 details.to_string(),
307 "googleapi: Error 400: bad\nDetails:\n[\n {\n \"@type\": \"t\\u003cx\\u003e\",\n \
308 \"empty\": {},\n \"list\": [\n 1,\n 2\n ],\n \"none\": []\n }\n]"
309 );
310 }
311
312 #[test]
313 fn check_response_passes_2xx_and_builds_the_error_otherwise() {
314 for status in [200, 201, 204, 299] {
315 assert!(
316 check_response(&parts(status), b"not json").is_ok(),
317 "{status}"
318 );
319 }
320 let mut p = parts(404);
321 p.headers
322 .insert("x-goog-request-id", http::HeaderValue::from_static("r1"));
323 let body = br#"{"error":{"code":404,"message":"gone","errors":[{"reason":"notFound","message":"gone"}],"details":[{"k":1}]}}"#;
324 let err = check_response(&p, body).unwrap_err();
325 assert_eq!(err.code, 404);
326 assert_eq!(err.message, "gone");
327 assert_eq!(err.details, vec![json!({"k": 1})]);
328 assert_eq!(err.body, String::from_utf8_lossy(body));
329 assert_eq!(err.header.get("x-goog-request-id").unwrap(), "r1");
330 let err = check_response(&parts(304), b"").unwrap_err();
332 assert_eq!(
333 err.to_string(),
334 "googleapi: got HTTP response code 304 with body: "
335 );
336 }
337
338 #[test]
339 fn api_error_from_response_reads_go_error_replies() {
340 let err =
342 api_error_from_response(&parts(400), br#"[{"error":{"code":409,"message":"dup"}}]"#);
343 assert_eq!((err.code, err.message.as_str()), (409, "dup"));
344 for body in [
346 &br#"{"error":{"code":0,"message":"m"}}"#[..],
347 br#"{"error":{"code":-1,"message":"m"}}"#,
348 br#"{"error":{"code":70000,"message":"m"}}"#,
349 ] {
350 assert_eq!(api_error_from_response(&parts(412), body).code, 412);
351 }
352 let err = api_error_from_response(
354 &parts(403),
355 br#"{"error":{"code":null,"message":null,"details":null,"errors":[null,{"reason":null,"message":"m"}]}}"#,
356 );
357 assert_eq!(err.code, 403);
358 assert_eq!(
359 err.errors,
360 vec![
361 ErrorItem::default(),
362 ErrorItem {
363 reason: String::new(),
364 message: "m".into(),
365 },
366 ]
367 );
368 for body in [
370 &b"down"[..],
371 b"[]",
372 br#"{"error":null}"#,
373 br#"{"error":"x"}"#,
374 ] {
375 let err = api_error_from_response(&parts(502), body);
376 assert_eq!(err.code, 502);
377 assert!(err.message.is_empty() && err.errors.is_empty());
378 assert_eq!(err.body, String::from_utf8_lossy(body));
379 }
380 }
381}