1use std::convert::Infallible;
2use std::time::Duration;
3
4use http::{HeaderMap, StatusCode};
5use thiserror::Error;
6
7#[derive(Debug, Error)]
9pub enum Error<E = Infallible> {
10 #[error("request validation failed at {field}: {message}")]
12 Validation {
13 field: String,
15 message: String,
17 },
18 #[error("invalid client configuration: {0}")]
20 Configuration(String),
21 #[error("HTTP transport failed: {0}")]
23 Transport(#[source] E),
24 #[error("HTTP attempt timed out (configured attempt limit: {timeout:?})")]
26 Timeout {
27 timeout: Duration,
29 },
30 #[error("failed to decode successful HTTP {status} response: {source}")]
32 Decode {
33 status: StatusCode,
35 request_id: Option<String>,
37 headers: Box<HeaderMap>,
39 body: Vec<u8>,
41 #[source]
43 source: serde_json::Error,
44 },
45 #[error("TypeSafe API returned HTTP {status} after {attempts} attempt(s)")]
47 Api {
48 status: StatusCode,
50 request_id: Option<String>,
52 headers: Box<HeaderMap>,
54 body: Vec<u8>,
56 retry_after: Option<Duration>,
58 attempts: u64,
60 },
61 #[error("evaluation event sequence ended without a terminal result")]
63 IncompleteEvaluation,
64}
65
66impl<E> Error<E> {
67 pub fn status(&self) -> Option<StatusCode> {
69 match self {
70 Self::Decode { status, .. } | Self::Api { status, .. } => Some(*status),
71 _ => None,
72 }
73 }
74
75 pub fn request_id(&self) -> Option<&str> {
77 match self {
78 Self::Decode { request_id, .. } | Self::Api { request_id, .. } => request_id.as_deref(),
79 _ => None,
80 }
81 }
82
83 pub fn body(&self) -> Option<&[u8]> {
85 match self {
86 Self::Decode { body, .. } | Self::Api { body, .. } => Some(body),
87 _ => None,
88 }
89 }
90
91 pub fn headers(&self) -> Option<&HeaderMap> {
93 match self {
94 Self::Decode { headers, .. } | Self::Api { headers, .. } => Some(headers.as_ref()),
95 _ => None,
96 }
97 }
98}
99
100impl Error<Infallible> {
101 pub fn with_transport<E>(self) -> Error<E>
105 where
106 E: std::error::Error + Send + Sync + 'static,
107 {
108 match self {
109 Self::Validation { field, message } => Error::Validation { field, message },
110 Self::Configuration(message) => Error::Configuration(message),
111 Self::Transport(never) => match never {},
112 Self::Timeout { timeout } => Error::Timeout { timeout },
113 Self::Decode {
114 status,
115 request_id,
116 headers,
117 body,
118 source,
119 } => Error::Decode {
120 status,
121 request_id,
122 headers,
123 body,
124 source,
125 },
126 Self::Api {
127 status,
128 request_id,
129 headers,
130 body,
131 retry_after,
132 attempts,
133 } => Error::Api {
134 status,
135 request_id,
136 headers,
137 body,
138 retry_after,
139 attempts,
140 },
141 Self::IncompleteEvaluation => Error::IncompleteEvaluation,
142 }
143 }
144}