1use std::collections::BTreeMap;
4use std::fmt;
5
6use jiff::{SignedDuration, Timestamp};
7use serde_json::Value;
8
9use crate::generated::types::TemplateLibraryConfirmationPerson;
10use crate::http::{HeaderMap, StatusCode};
11
12const MAX_SOURCE_CHAIN_DEPTH: usize = 32;
14
15pub const MAX_ERROR_MESSAGE_LENGTH: usize = 500;
17pub const MAX_ERROR_BODY_BYTES: usize = 1_048_576;
19pub const MAX_RETRY_AFTER_SECONDS: u32 = 2_147_483_647;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24#[non_exhaustive]
25pub enum ErrorCode {
26 Usage,
28 NotFound,
30 AuthRequired,
32 Forbidden,
34 RateLimit,
36 Network,
38 ApiError,
40 Ambiguous,
42 Validation,
44 LimitExceeded,
46}
47
48impl ErrorCode {
49 pub fn as_str(&self) -> &'static str {
51 match self {
52 ErrorCode::Usage => "usage",
53 ErrorCode::NotFound => "not_found",
54 ErrorCode::AuthRequired => "auth_required",
55 ErrorCode::Forbidden => "forbidden",
56 ErrorCode::RateLimit => "rate_limit",
57 ErrorCode::Network => "network",
58 ErrorCode::ApiError => "api_error",
59 ErrorCode::Ambiguous => "ambiguous",
60 ErrorCode::Validation => "validation",
61 ErrorCode::LimitExceeded => "limit_exceeded",
62 }
63 }
64
65 pub fn exit_code(&self) -> i32 {
67 match self {
68 ErrorCode::Usage => 1,
69 ErrorCode::NotFound => 2,
70 ErrorCode::AuthRequired => 3,
71 ErrorCode::Forbidden => 4,
72 ErrorCode::RateLimit => 5,
73 ErrorCode::Network => 6,
74 ErrorCode::ApiError => 7,
75 ErrorCode::Ambiguous => 8,
76 ErrorCode::Validation => 9,
77 ErrorCode::LimitExceeded => 10,
78 }
79 }
80}
81
82impl fmt::Display for ErrorCode {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 f.write_str(self.as_str())
85 }
86}
87
88#[derive(thiserror::Error)]
93#[error("{}", self.render())]
94pub struct Error {
95 inner: Box<Inner>,
96 #[source]
97 source: Option<Box<dyn std::error::Error + Send + Sync>>,
98}
99
100struct Inner {
101 code: ErrorCode,
102 message: String,
103 hint: Option<String>,
104 http_status: Option<u16>,
105 retryable: bool,
106 retry_after: Option<u32>,
107 request_id: Option<String>,
108 field_errors: Option<BTreeMap<String, Vec<String>>>,
109 confirmation_people: Option<Vec<TemplateLibraryConfirmationPerson>>,
110 response_too_large: bool,
111 deadline_exceeded: bool,
112 timeout: bool,
113 body: Option<Box<[u8]>>,
114}
115
116impl Error {
117 pub fn new(code: ErrorCode, message: impl Into<String>) -> Error {
120 Error {
121 inner: Box::new(Inner {
122 code,
123 message: truncate(&message.into()),
124 hint: None,
125 http_status: None,
126 retryable: false,
127 retry_after: None,
128 request_id: None,
129 field_errors: None,
130 confirmation_people: None,
131 response_too_large: false,
132 deadline_exceeded: false,
133 timeout: false,
134 body: None,
135 }),
136 source: None,
137 }
138 }
139
140 pub fn network_timeout(source: impl std::error::Error + Send + Sync + 'static) -> Error {
144 let mut error = Error::network(source);
145 error.inner.timeout = true;
146 error
147 }
148
149 pub fn usage(message: impl Into<String>) -> Error {
151 Error::new(ErrorCode::Usage, message)
152 }
153
154 pub fn network(source: impl std::error::Error + Send + Sync + 'static) -> Error {
156 Error::new(ErrorCode::Network, "Network error")
157 .with_hint(source.to_string())
158 .retryable(true)
159 .with_source(source)
160 }
161
162 pub fn network_at(origin: &str) -> Error {
165 Error::new(
166 ErrorCode::Network,
167 format!("Network error contacting {origin}"),
168 )
169 .retryable(true)
170 }
171
172 pub fn malformed_response(detail: impl Into<String>) -> Error {
175 Error::new(
176 ErrorCode::ApiError,
177 truncate(&format!("malformed response: {}", detail.into())),
178 )
179 }
180
181 pub fn response_too_large(limit: usize) -> Error {
183 let mut error = Error::new(
184 ErrorCode::ApiError,
185 format!("response body exceeds {limit} bytes"),
186 );
187 error.inner.response_too_large = true;
188 error
189 }
190
191 pub fn deadline_exceeded(after: std::time::Duration) -> Error {
193 let mut error = Error::new(
194 ErrorCode::Network,
195 format!("operation deadline of {after:?} exceeded"),
196 );
197 error.inner.deadline_exceeded = true;
198 error
199 }
200
201 pub fn from_response(status: StatusCode, headers: &HeaderMap, body: &[u8]) -> Error {
204 let status_code = status.as_u16();
205 let (code, retryable) = match status_code {
206 401 => (ErrorCode::AuthRequired, false),
207 403 => (ErrorCode::Forbidden, false),
208 404 => (ErrorCode::NotFound, false),
209 429 => (ErrorCode::RateLimit, true),
210 400 | 422 => (ErrorCode::Validation, false),
211 500 | 502 | 503 | 504 => (ErrorCode::ApiError, true),
212 507 => (ErrorCode::LimitExceeded, false),
213 code if code >= 500 => (ErrorCode::ApiError, true),
214 _ => (ErrorCode::ApiError, false),
215 };
216 let parsed = serde_json::from_slice::<Value>(body).ok();
217 let scalar = parsed
218 .as_ref()
219 .and_then(|value| value.get("error").and_then(Value::as_str))
220 .or_else(|| {
221 parsed
222 .as_ref()
223 .and_then(|value| value.get("message").and_then(Value::as_str))
224 })
225 .map(str::to_string);
226 let mut message = scalar
227 .clone()
228 .unwrap_or_else(|| format!("Request failed (HTTP {status_code})"));
229 let hint = parsed
230 .as_ref()
231 .and_then(|value| value.get("error_description").and_then(Value::as_str))
232 .map(truncate);
233
234 let field_errors = match (status_code, &parsed) {
235 (400 | 422, Some(value)) => field_errors_of(value),
236 _ => None,
237 };
238 if let Some(fields) = &field_errors {
239 let flattened = flatten(fields);
240 message = match scalar {
241 Some(_) => format!("{message} ({flattened})"),
242 None => flattened,
243 };
244 }
245 let confirmation_people = match (status_code, &parsed) {
246 (422, Some(value)) => confirmation_people_of(value),
247 _ => None,
248 };
249
250 let mut error = Error::new(code, truncate(&message))
251 .retryable(retryable)
252 .with_status(status_code);
253 error.inner.hint = hint;
254 error.inner.retry_after = parse_retry_after_header(headers, Timestamp::now());
255 error.inner.request_id = headers
256 .get("x-request-id")
257 .and_then(|value| value.to_str().ok())
258 .map(truncate);
259 error.inner.field_errors = field_errors;
260 error.inner.confirmation_people = confirmation_people;
261 if !body.is_empty() {
262 let kept = body.len().min(MAX_ERROR_BODY_BYTES);
263 error.inner.body = Some(Box::from(&body[..kept]));
264 }
265 error
266 }
267
268 pub(crate) fn find_source<T: std::error::Error + 'static>(&self) -> Option<&T> {
277 let mut current = std::error::Error::source(self);
278 for _ in 0..MAX_SOURCE_CHAIN_DEPTH {
279 let error = current?;
280 if let Some(found) = error.downcast_ref::<T>() {
281 return Some(found);
282 }
283 current = error.source();
284 }
285 None
286 }
287
288 pub(crate) fn duplicate(&self) -> Error {
296 Error {
297 inner: Box::new(Inner {
298 code: self.inner.code,
299 message: self.inner.message.clone(),
300 hint: self.inner.hint.clone(),
301 http_status: self.inner.http_status,
302 retryable: self.inner.retryable,
303 retry_after: self.inner.retry_after,
304 request_id: self.inner.request_id.clone(),
305 field_errors: self.inner.field_errors.clone(),
306 confirmation_people: self.inner.confirmation_people.clone(),
307 response_too_large: self.inner.response_too_large,
308 deadline_exceeded: self.inner.deadline_exceeded,
309 timeout: self.inner.timeout,
310 body: self.inner.body.clone(),
311 }),
312 source: None,
313 }
314 }
315
316 pub(crate) fn with_context(mut self, context: impl fmt::Display) -> Error {
321 self.inner.message = truncate(&format!("{context}: {}", self.inner.message));
322 self
323 }
324
325 pub fn with_hint(mut self, hint: impl Into<String>) -> Error {
328 self.inner.hint = Some(truncate(&hint.into()));
329 self
330 }
331
332 pub fn with_status(mut self, status: u16) -> Error {
334 self.inner.http_status = Some(status);
335 self
336 }
337
338 pub fn with_request_id(mut self, request_id: impl Into<String>) -> Error {
341 self.inner.request_id = Some(truncate(&request_id.into()));
342 self
343 }
344
345 pub fn with_retry_after(mut self, seconds: u32) -> Error {
347 self.inner.retry_after = Some(seconds);
348 self
349 }
350
351 pub(crate) fn timed_out(mut self) -> Error {
354 self.inner.timeout = true;
355 self
356 }
357
358 pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Error {
360 self.source = Some(Box::new(source));
361 self
362 }
363
364 pub fn retryable(mut self, retryable: bool) -> Error {
366 self.inner.retryable = retryable;
367 self
368 }
369
370 pub fn code(&self) -> ErrorCode {
372 self.inner.code
373 }
374
375 pub fn message(&self) -> &str {
377 &self.inner.message
378 }
379
380 pub fn hint(&self) -> Option<&str> {
382 self.inner.hint.as_deref()
383 }
384
385 pub fn http_status(&self) -> Option<u16> {
387 self.inner.http_status
388 }
389
390 pub fn is_retryable(&self) -> bool {
392 self.inner.retryable
393 }
394
395 pub fn retry_after(&self) -> Option<u32> {
397 self.inner.retry_after
398 }
399
400 pub fn request_id(&self) -> Option<&str> {
402 self.inner.request_id.as_deref()
403 }
404
405 pub fn field_errors(&self) -> Option<&BTreeMap<String, Vec<String>>> {
408 self.inner.field_errors.as_ref()
409 }
410
411 pub fn confirmation_people(&self) -> Option<&[TemplateLibraryConfirmationPerson]> {
413 self.inner.confirmation_people.as_deref()
414 }
415
416 pub fn exit_code(&self) -> i32 {
418 self.inner.code.exit_code()
419 }
420
421 pub fn body(&self) -> Option<&[u8]> {
423 self.inner.body.as_deref()
424 }
425
426 pub fn is_response_too_large(&self) -> bool {
428 self.inner.response_too_large
429 }
430
431 pub fn is_deadline_exceeded(&self) -> bool {
433 self.inner.deadline_exceeded
434 }
435
436 pub fn is_timeout(&self) -> bool {
438 self.inner.timeout
439 }
440
441 fn render(&self) -> String {
442 match &self.inner.hint {
443 Some(hint) => format!("{}: {hint}", self.inner.message),
444 None => self.inner.message.clone(),
445 }
446 }
447}
448
449impl fmt::Debug for Error {
450 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451 f.debug_struct("Error")
452 .field("code", &self.inner.code)
453 .field("message", &self.inner.message)
454 .field("hint", &self.inner.hint)
455 .field("http_status", &self.inner.http_status)
456 .field("retryable", &self.inner.retryable)
457 .field("retry_after", &self.inner.retry_after)
458 .field("request_id", &self.inner.request_id)
459 .field("field_errors", &self.inner.field_errors)
460 .finish_non_exhaustive()
461 }
462}
463
464pub fn truncate(message: &str) -> String {
468 if message.len() <= MAX_ERROR_MESSAGE_LENGTH {
469 return message.to_string();
470 }
471 let mut end = MAX_ERROR_MESSAGE_LENGTH - 3;
472 while !message.is_char_boundary(end) {
473 end -= 1;
474 }
475 format!("{}...", &message[..end])
476}
477
478fn field_errors_of(body: &Value) -> Option<BTreeMap<String, Vec<String>>> {
480 let object = body.as_object()?;
481 match object.get("errors") {
482 Some(Value::Object(fields)) => {
483 let mut map = BTreeMap::new();
484 for (field, messages) in fields {
485 if let Some(messages) = messages.as_array() {
486 let kept: Vec<String> = messages
487 .iter()
488 .filter_map(Value::as_str)
489 .map(str::to_string)
490 .collect();
491 if !kept.is_empty() {
492 map.insert(field.clone(), kept);
493 }
494 }
495 }
496 (!map.is_empty()).then_some(map)
497 }
498 Some(Value::Array(rows)) => row_keyed(rows),
499 Some(_) => None,
500 None => {
501 if object.is_empty() {
502 return None;
503 }
504 let mut map = BTreeMap::new();
505 for (field, messages) in object {
506 let messages = messages.as_array()?;
507 if messages.is_empty() {
508 return None;
509 }
510 let mut kept = Vec::new();
511 for message in messages {
512 match message.as_str() {
513 Some(text) if !text.is_empty() => kept.push(text.to_string()),
514 _ => return None,
515 }
516 }
517 map.insert(field.clone(), kept);
518 }
519 Some(map)
520 }
521 }
522}
523
524fn row_keyed(rows: &[Value]) -> Option<BTreeMap<String, Vec<String>>> {
527 if rows.is_empty() {
528 return None;
529 }
530 let mut map: BTreeMap<String, Vec<String>> = BTreeMap::new();
531 for (position, row) in rows.iter().enumerate() {
532 let object = row.as_object()?;
533 let messages: Vec<String> = object
534 .get("messages")?
535 .as_array()?
536 .iter()
537 .filter_map(Value::as_str)
538 .filter(|text| !text.is_empty())
539 .map(str::to_string)
540 .collect();
541 if messages.is_empty() {
542 return None;
543 }
544 let key = match object.get("email_address").and_then(Value::as_str) {
545 Some(address) if !address.is_empty() => address.to_string(),
546 _ => match object.get("index").and_then(Value::as_i64) {
547 Some(index) => index.to_string(),
548 None => position.to_string(),
549 },
550 };
551 map.entry(key).or_default().extend(messages);
552 }
553 Some(map)
554}
555
556fn flatten(fields: &BTreeMap<String, Vec<String>>) -> String {
558 fields
559 .iter()
560 .map(|(field, messages)| format!("{field}: {}", messages.join("; ")))
561 .collect::<Vec<_>>()
562 .join(", ")
563}
564
565fn confirmation_people_of(body: &Value) -> Option<Vec<TemplateLibraryConfirmationPerson>> {
566 let people = body.get("people")?.as_array()?;
567 if people.is_empty() {
568 return None;
569 }
570 let mut result = Vec::new();
571 for person in people {
572 let object = person.as_object()?;
573 let id = object.get("id")?.as_i64()?;
574 let name = object.get("name")?.as_str()?;
575 let avatar_url = object.get("avatar_url")?.as_str()?;
576 if id <= 0 || name.is_empty() || avatar_url.is_empty() {
577 return None;
578 }
579 result.push(serde_json::from_value(person.clone()).ok()?);
580 }
581 Some(result)
582}
583
584pub fn parse_retry_after(value: &str, now: Timestamp) -> Option<u32> {
589 let value = value.trim_matches([' ', '\t']);
590 if value.is_empty() {
591 return None;
592 }
593 if value.bytes().all(|b| b.is_ascii_digit()) {
594 let seconds = match value.parse::<u64>() {
595 Ok(seconds) => seconds.min(u64::from(MAX_RETRY_AFTER_SECONDS)),
596 Err(_) => u64::from(MAX_RETRY_AFTER_SECONDS),
597 };
598 return (seconds > 0).then(|| u32::try_from(seconds).unwrap_or(MAX_RETRY_AFTER_SECONDS));
599 }
600 let until = parse_http_date(value)?;
601 let left = until.duration_since(now);
602 let whole = left.as_secs();
603 let started = left > SignedDuration::from_secs(whole);
604 if whole < 0 || (whole == 0 && !started) {
605 return None;
606 }
607 let seconds = whole.saturating_add(i64::from(started));
608 Some(
609 u32::try_from(seconds)
610 .unwrap_or(MAX_RETRY_AFTER_SECONDS)
611 .min(MAX_RETRY_AFTER_SECONDS),
612 )
613}
614
615fn parse_http_date(value: &str) -> Option<Timestamp> {
619 let collapsed: String = value.split_whitespace().collect::<Vec<_>>().join(" ");
620 for format in [
621 "%a, %d %b %Y %H:%M:%S GMT",
622 "%A, %d-%b-%y %H:%M:%S GMT",
623 "%a %b %d %H:%M:%S %Y",
624 ] {
625 if let Ok(civil) = jiff::civil::DateTime::strptime(format, &collapsed) {
626 return jiff::tz::Offset::UTC.to_timestamp(civil).ok();
627 }
628 }
629 None
630}
631
632pub(crate) fn parse_retry_after_header(headers: &HeaderMap, now: Timestamp) -> Option<u32> {
634 headers
635 .get("retry-after")
636 .and_then(|value| value.to_str().ok())
637 .and_then(|value| parse_retry_after(value, now))
638}
639
640#[cfg(test)]
641mod tests {
642 use super::*;
643 use crate::http::HeaderValue;
644
645 fn at(seconds: i64) -> Timestamp {
646 Timestamp::from_second(1_700_000_000 + seconds).unwrap()
647 }
648
649 fn headers(pairs: &[(&str, &str)]) -> HeaderMap {
650 let mut headers = HeaderMap::new();
651 for (name, value) in pairs {
652 headers.insert(
653 crate::http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
654 HeaderValue::from_str(value).unwrap(),
655 );
656 }
657 headers
658 }
659
660 #[test]
661 fn retry_after_digits_saturate_and_zero_falls_through() {
662 assert_eq!(parse_retry_after("5", at(0)), Some(5));
663 assert_eq!(parse_retry_after(" 5 ", at(0)), Some(5));
664 assert_eq!(parse_retry_after("0", at(0)), None);
665 assert_eq!(parse_retry_after("+5", at(0)), None);
666 assert_eq!(parse_retry_after("-5", at(0)), None);
667 assert_eq!(parse_retry_after("2.5", at(0)), None);
668 assert_eq!(parse_retry_after("5s", at(0)), None);
669 assert_eq!(parse_retry_after("2147483647", at(0)), Some(2_147_483_647));
670 assert_eq!(parse_retry_after("2147483648", at(0)), Some(2_147_483_647));
671 assert_eq!(
672 parse_retry_after("99999999999999999999999999", at(0)),
673 Some(2_147_483_647)
674 );
675 assert_eq!(parse_retry_after("", at(0)), None);
676 }
677
678 #[test]
679 fn retry_after_dates_round_up_and_past_dates_fall_through() {
680 let now = "2021-06-09T10:18:14.250Z".parse::<Timestamp>().unwrap();
681 assert_eq!(
682 parse_retry_after("Wed, 09 Jun 2021 10:18:16 GMT", now),
683 Some(2)
684 );
685 assert_eq!(
686 parse_retry_after("Wed, 09 Jun 2021 10:18:15 GMT", now),
687 Some(1)
688 );
689 assert_eq!(
690 parse_retry_after("Wed, 09 Jun 2021 10:18:14 GMT", now),
691 None
692 );
693 let just_before = "2021-06-09T10:18:14.999999999Z"
694 .parse::<Timestamp>()
695 .unwrap();
696 assert_eq!(
697 parse_retry_after("Wed, 09 Jun 2021 10:18:15 GMT", just_before),
698 Some(1)
699 );
700 let just_after = "2021-06-09T10:18:13.999999999Z"
701 .parse::<Timestamp>()
702 .unwrap();
703 assert_eq!(
704 parse_retry_after("Wed, 09 Jun 2021 10:18:15 GMT", just_after),
705 Some(2)
706 );
707 assert_eq!(
708 parse_retry_after("Wed, 09 Jun 2021 09:00:00 GMT", now),
709 None
710 );
711 assert_eq!(
712 parse_retry_after("Wednesday, 09-Jun-21 10:18:16 GMT", now),
713 Some(2)
714 );
715 assert_eq!(parse_retry_after("Wed Jun 9 10:18:16 2021", now), Some(2));
716 assert_eq!(
717 parse_retry_after("Tue, 31 Dec 2999 00:00:00 GMT", now),
718 Some(2_147_483_647)
719 );
720 for not_http_date in [
721 "Wed, 09 Jun 2021 10:18:16 -0500",
722 "Wed, 09 Jun 2021 10:18:16 +0000",
723 "Wed, 09 Jun 2021 10:18:16 UT",
724 "Wed, 09 Jun 2021 10:18:16 EST",
725 "Wed, 09 Jun 2021 10:18:16 Z",
726 "09 Jun 2021 10:18:16 GMT",
727 "Wed, 09 Jun 21 10:18:16 GMT",
728 ] {
729 assert_eq!(
730 parse_retry_after(not_http_date, now),
731 None,
732 "{not_http_date} is RFC 2822, not an HTTP-date"
733 );
734 }
735 assert_eq!(parse_retry_after("not a date", now), None);
736 }
737
738 #[test]
739 fn statuses_map_to_codes_in_order() {
740 let cases = [
741 (401, ErrorCode::AuthRequired, false),
742 (403, ErrorCode::Forbidden, false),
743 (404, ErrorCode::NotFound, false),
744 (429, ErrorCode::RateLimit, true),
745 (400, ErrorCode::Validation, false),
746 (422, ErrorCode::Validation, false),
747 (500, ErrorCode::ApiError, true),
748 (502, ErrorCode::ApiError, true),
749 (503, ErrorCode::ApiError, true),
750 (504, ErrorCode::ApiError, true),
751 (507, ErrorCode::LimitExceeded, false),
752 (599, ErrorCode::ApiError, true),
753 (418, ErrorCode::ApiError, false),
754 ];
755 for (status, code, retryable) in cases {
756 let error = Error::from_response(
757 StatusCode::from_u16(status).unwrap(),
758 &headers(&[("x-request-id", "req-1")]),
759 b"",
760 );
761 assert_eq!(error.code(), code, "{status}");
762 assert_eq!(error.is_retryable(), retryable, "{status}");
763 assert_eq!(error.http_status(), Some(status));
764 assert_eq!(error.request_id(), Some("req-1"));
765 assert_eq!(error.message(), format!("Request failed (HTTP {status})"));
766 }
767 }
768
769 #[test]
770 fn a_composed_validation_message_is_truncated_once() {
771 let scalar = format!("{}\u{20ac}bb", "a".repeat(MAX_ERROR_MESSAGE_LENGTH - 4));
774 let body = serde_json::json!({"error": scalar, "errors": {"name": ["x"]}}).to_string();
775 let error = Error::from_response(
776 StatusCode::UNPROCESSABLE_ENTITY,
777 &HeaderMap::new(),
778 body.as_bytes(),
779 );
780 assert_eq!(
781 error.message(),
782 format!("{}...", "a".repeat(MAX_ERROR_MESSAGE_LENGTH - 4))
783 );
784 assert_eq!(error.field_errors().unwrap()["name"], vec!["x".to_string()]);
785 }
786
787 #[test]
788 fn request_id_read_off_a_response_is_bounded_like_the_setter() {
789 let long = "r".repeat(MAX_ERROR_MESSAGE_LENGTH + 1);
790 let error = Error::from_response(
791 StatusCode::BAD_GATEWAY,
792 &headers(&[("x-request-id", &long)]),
793 b"",
794 );
795 let expected = Error::usage("x").with_request_id(&long);
796 assert_eq!(error.request_id(), expected.request_id());
797 assert_eq!(error.request_id().unwrap().len(), MAX_ERROR_MESSAGE_LENGTH);
798 assert!(error.request_id().unwrap().ends_with("..."));
799 }
800
801 #[test]
802 fn retry_after_is_read_at_every_status() {
803 let error = Error::from_response(
804 StatusCode::SERVICE_UNAVAILABLE,
805 &headers(&[("retry-after", "7")]),
806 b"{}",
807 );
808 assert_eq!(error.retry_after(), Some(7));
809 let error = Error::from_response(
810 StatusCode::NOT_FOUND,
811 &headers(&[("retry-after", "3")]),
812 b"",
813 );
814 assert_eq!(error.retry_after(), Some(3));
815 }
816
817 #[test]
818 fn bodies_supply_message_and_hint() {
819 let error = Error::from_response(
820 StatusCode::UNAUTHORIZED,
821 &headers(&[]),
822 br#"{"error": "Unauthorized", "error_description": "token expired"}"#,
823 );
824 assert_eq!(error.message(), "Unauthorized");
825 assert_eq!(error.hint(), Some("token expired"));
826 let error = Error::from_response(
827 StatusCode::NOT_FOUND,
828 &headers(&[]),
829 br#"{"message": "Not found"}"#,
830 );
831 assert_eq!(error.message(), "Not found");
832 let error = Error::from_response(StatusCode::NOT_FOUND, &headers(&[]), b"<html>");
833 assert_eq!(error.message(), "Request failed (HTTP 404)");
834 let long = format!(r#"{{"error": "{}"}}"#, "x".repeat(600));
835 let error = Error::from_response(StatusCode::BAD_REQUEST, &headers(&[]), long.as_bytes());
836 assert_eq!(error.message().chars().count(), 500);
837 assert!(error.message().ends_with("..."));
838 }
839
840 #[test]
841 fn field_keyed_bodies_are_flattened_and_exposed() {
842 let error = Error::from_response(
843 StatusCode::UNPROCESSABLE_ENTITY,
844 &headers(&[]),
845 br#"{"error": "Validation failed", "errors": {"color": ["is not a valid color"], "name": ["can't be blank", "is too short"]}}"#,
846 );
847 assert_eq!(error.code(), ErrorCode::Validation);
848 assert_eq!(
849 error.message(),
850 "Validation failed (color: is not a valid color, name: can't be blank; is too short)"
851 );
852 assert_eq!(
853 error.field_errors().unwrap()["name"],
854 vec!["can't be blank", "is too short"]
855 );
856
857 let error = Error::from_response(
858 StatusCode::BAD_REQUEST,
859 &headers(&[]),
860 br#"{"payload_url": ["is not a valid URL"]}"#,
861 );
862 assert_eq!(error.message(), "payload_url: is not a valid URL");
863 assert_eq!(error.field_errors().unwrap().len(), 1);
864
865 let error = Error::from_response(
866 StatusCode::BAD_REQUEST,
867 &headers(&[]),
868 br#"{"error": "Webhook is invalid", "payload_url": ["is invalid"]}"#,
869 );
870 assert_eq!(error.message(), "Webhook is invalid");
871 assert!(error.field_errors().is_none());
872
873 let error = Error::from_response(
874 StatusCode::UNPROCESSABLE_ENTITY,
875 &headers(&[]),
876 br#"{"error": {}, "errors": {"base": ["Can't be undocked"], "__proto__": ["x"]}}"#,
877 );
878 assert_eq!(error.message(), "__proto__: x, base: Can't be undocked");
879
880 let error = Error::from_response(
881 StatusCode::NOT_FOUND,
882 &headers(&[]),
883 br#"{"errors": {"x": ["y"]}}"#,
884 );
885 assert!(error.field_errors().is_none());
886 }
887
888 #[test]
889 fn a_server_message_that_looks_synthetic_is_still_composed() {
890 let error = Error::from_response(
891 StatusCode::UNPROCESSABLE_ENTITY,
892 &headers(&[]),
893 br#"{"error": "Request failed (HTTP 422) upstream", "errors": {"x": ["y"]}}"#,
894 );
895 assert_eq!(error.message(), "Request failed (HTTP 422) upstream (x: y)");
896 }
897
898 #[test]
899 fn row_keyed_bodies_land_on_addresses_indexes_then_positions() {
900 let error = Error::from_response(
901 StatusCode::UNPROCESSABLE_ENTITY,
902 &headers(&[]),
903 br#"{"errors": [{"email_address": "not-an-address", "messages": ["Email address must be valid"]}, {"email_address": null, "messages": ["Email address can't be blank"]}, {"index": 7, "messages": ["Name can't be blank"]}, {"email_address": "not-an-address", "messages": ["Already invited"]}]}"#,
904 );
905 let fields = error.field_errors().unwrap();
906 assert_eq!(
907 fields["not-an-address"],
908 vec!["Email address must be valid", "Already invited"]
909 );
910 assert_eq!(fields["1"], vec!["Email address can't be blank"]);
911 assert_eq!(fields["7"], vec!["Name can't be blank"]);
912 assert_eq!(
913 error.message(),
914 "1: Email address can't be blank, 7: Name can't be blank, not-an-address: Email address must be valid; Already invited"
915 );
916
917 let error = Error::from_response(
918 StatusCode::UNPROCESSABLE_ENTITY,
919 &headers(&[]),
920 br#"{"errors": [{"email_address": "a", "messages": ["x"]}, {"email_address": "b"}]}"#,
921 );
922 assert!(error.field_errors().is_none());
923 assert_eq!(error.message(), "Request failed (HTTP 422)");
924 }
925
926 #[test]
927 fn confirmation_people_are_projected_only_when_every_entry_conforms() {
928 let error = Error::from_response(
929 StatusCode::UNPROCESSABLE_ENTITY,
930 &headers(&[]),
931 br#"{"error": "Confirmation required", "people": [{"id": 1, "name": "Ann", "avatar_url": "https://x/a.png"}]}"#,
932 );
933 assert_eq!(error.code(), ErrorCode::Validation);
934 assert_eq!(error.confirmation_people().unwrap().len(), 1);
935 assert_eq!(error.confirmation_people().unwrap()[0].id, 1);
936
937 let error = Error::from_response(
938 StatusCode::UNPROCESSABLE_ENTITY,
939 &headers(&[]),
940 br#"{"error": "x", "people": [{"id": 0, "name": "Ann", "avatar_url": "u"}]}"#,
941 );
942 assert!(error.confirmation_people().is_none());
943 }
944
945 #[test]
946 fn errors_are_send_and_sync() {
947 fn assert_send_sync<T: Send + Sync>() {}
948 assert_send_sync::<Error>();
949 }
950}