1use thiserror::Error;
2
3#[derive(Debug, Error, PartialEq)]
4pub enum ApiError {
5 #[error("encountered an unknown error code from the API: `{0}`")]
6 UnknownApiErrorCode(u16),
7}
8
9#[derive(Debug, PartialEq)]
10pub enum ApiErrorCode {
11 Accepted,
12 ResourceNotFound,
13 InvalidQuery,
14 RateLimitExceeded,
15 InternalError,
16 UnexpectedContentType,
17 Forbidden,
18 TemporarilyUnavailable,
19 Unauthorized,
20 MethodNotAllowed,
21 UnprocessableEntity,
22}
23
24impl TryFrom<u16> for ApiErrorCode {
25 type Error = ApiError;
26
27 fn try_from(value: u16) -> Result<Self, Self::Error> {
28 match value {
29 0 => Ok(ApiErrorCode::Accepted),
30 1 => Ok(ApiErrorCode::ResourceNotFound),
31 2 => Ok(ApiErrorCode::InvalidQuery),
32 3 => Ok(ApiErrorCode::RateLimitExceeded),
33 4 => Ok(ApiErrorCode::InternalError),
34 5 => Ok(ApiErrorCode::UnexpectedContentType),
35 6 => Ok(ApiErrorCode::Forbidden),
36 7 => Ok(ApiErrorCode::TemporarilyUnavailable),
37 8 => Ok(ApiErrorCode::Unauthorized),
38 9 => Ok(ApiErrorCode::MethodNotAllowed),
39 10 => Ok(ApiErrorCode::UnprocessableEntity),
40 _ => Err(ApiError::UnknownApiErrorCode(value)),
41 }
42 }
43}
44
45#[cfg(test)]
46mod tests {
47 use crate::errorcode::{ApiError, ApiErrorCode};
48
49 #[test]
50 fn test_api_error_codes() {
51 assert_eq!(ApiErrorCode::Accepted, ApiErrorCode::try_from(0).unwrap());
52 assert_eq!(
53 ApiErrorCode::ResourceNotFound,
54 ApiErrorCode::try_from(1).unwrap()
55 );
56 assert_eq!(
57 ApiErrorCode::InvalidQuery,
58 ApiErrorCode::try_from(2).unwrap()
59 );
60 assert_eq!(
61 ApiErrorCode::RateLimitExceeded,
62 ApiErrorCode::try_from(3).unwrap()
63 );
64 assert_eq!(
65 ApiErrorCode::InternalError,
66 ApiErrorCode::try_from(4).unwrap()
67 );
68 assert_eq!(
69 ApiErrorCode::UnexpectedContentType,
70 ApiErrorCode::try_from(5).unwrap()
71 );
72 assert_eq!(ApiErrorCode::Forbidden, ApiErrorCode::try_from(6).unwrap());
73 assert_eq!(
74 ApiErrorCode::TemporarilyUnavailable,
75 ApiErrorCode::try_from(7).unwrap()
76 );
77 assert_eq!(
78 ApiErrorCode::Unauthorized,
79 ApiErrorCode::try_from(8).unwrap()
80 );
81 assert_eq!(
82 ApiErrorCode::MethodNotAllowed,
83 ApiErrorCode::try_from(9).unwrap()
84 );
85 assert_eq!(
86 ApiErrorCode::UnprocessableEntity,
87 ApiErrorCode::try_from(10).unwrap()
88 );
89
90 assert_eq!(true, ApiErrorCode::try_from(100).is_err());
91 assert_eq!(
92 ApiError::UnknownApiErrorCode(100),
93 ApiErrorCode::try_from(100).unwrap_err()
94 );
95 }
96}