1use std::env::VarError;
2use std::error::Error;
3use std::fmt::{Display, Formatter};
4use std::num::ParseIntError;
5
6use chrono::OutOfRangeError;
7use reqwest::Response;
8
9#[derive(Debug)]
10pub enum GrowthbookErrorCode {
11 GenericError,
12 SerdeDeserialize,
13 ParseError,
14 DurationOutOfRangeError,
15 MissingEnvironmentVariable,
16 GrowthbookGateway,
17 GrowthbookGatewayDeserialize,
18 InvalidResponseValueType,
19 GrowthBookAttributeIsNotObject,
20 ConfigError,
21}
22
23#[derive(Debug)]
24pub struct GrowthbookError {
25 pub code: GrowthbookErrorCode,
26 pub message: String,
27}
28
29impl GrowthbookError {
30 pub fn new(
31 code: GrowthbookErrorCode,
32 message: &str,
33 ) -> Self {
34 GrowthbookError { code, message: String::from(message) }
35 }
36}
37
38impl Display for GrowthbookError {
39 fn fmt(
40 &self,
41 f: &mut Formatter<'_>,
42 ) -> std::fmt::Result {
43 write!(f, "{}", self.message)
44 }
45}
46
47impl Error for GrowthbookError {
48 fn description(&self) -> &str {
49 &self.message
50 }
51}
52
53impl From<Box<dyn Error>> for GrowthbookError {
54 fn from(error: Box<dyn Error>) -> Self {
55 Self {
56 code: GrowthbookErrorCode::GenericError,
57 message: error.to_string(),
58 }
59 }
60}
61
62impl From<reqwest_middleware::Error> for GrowthbookError {
63 fn from(error: reqwest_middleware::Error) -> Self {
64 Self {
65 code: GrowthbookErrorCode::GrowthbookGateway,
66 message: error.to_string(),
67 }
68 }
69}
70
71impl From<reqwest::Error> for GrowthbookError {
72 fn from(error: reqwest::Error) -> Self {
73 Self {
74 code: GrowthbookErrorCode::GrowthbookGatewayDeserialize,
75 message: error.to_string(),
76 }
77 }
78}
79
80impl From<VarError> for GrowthbookError {
81 fn from(error: VarError) -> Self {
82 Self {
83 code: GrowthbookErrorCode::MissingEnvironmentVariable,
84 message: error.to_string(),
85 }
86 }
87}
88
89impl From<ParseIntError> for GrowthbookError {
90 fn from(error: ParseIntError) -> Self {
91 Self {
92 code: GrowthbookErrorCode::ParseError,
93 message: error.to_string(),
94 }
95 }
96}
97
98impl From<serde_json::Error> for GrowthbookError {
99 fn from(error: serde_json::Error) -> Self {
100 Self {
101 code: GrowthbookErrorCode::ParseError,
102 message: error.to_string(),
103 }
104 }
105}
106
107impl From<OutOfRangeError> for GrowthbookError {
108 fn from(error: OutOfRangeError) -> Self {
109 Self {
110 code: GrowthbookErrorCode::DurationOutOfRangeError,
111 message: error.to_string(),
112 }
113 }
114}
115
116impl From<Response> for GrowthbookError {
117 fn from(response: Response) -> Self {
118 Self {
119 code: GrowthbookErrorCode::GrowthbookGateway,
120 message: format!("Failed to get features. StatusCode={}", response.status()),
121 }
122 }
123}