1use reqwest::header::InvalidHeaderValue;
4use reqwest::Error as ReqwestError;
5use serde::Serialize;
6use std::error::Error;
7use std::fmt;
8use url::ParseError;
9
10#[derive(Debug, Serialize)]
11pub struct DfnsError {
12 pub http_status: u16,
13 pub message: String,
14 #[serde(skip_serializing_if = "Option::is_none")]
15 pub context: Option<serde_json::Value>,
16}
17
18impl DfnsError {
19 pub fn new(
20 http_status: u16,
21 message: impl Into<String>,
22 context: Option<serde_json::Value>,
23 ) -> Self {
24 Self {
25 http_status,
26 message: message.into(),
27 context,
28 }
29 }
30}
31
32impl fmt::Display for DfnsError {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 let error_json = serde_json::json!({
35 "httpStatus": self.http_status,
36 "message": self.message,
37 "context": self.context,
38 });
39 write!(
40 f,
41 "{}",
42 serde_json::to_string_pretty(&error_json).unwrap_or_default()
43 )
44 }
45}
46
47impl Error for DfnsError {}
48
49#[derive(Debug, Serialize)]
50pub struct PolicyPendingError {
51 pub http_status: u16,
52 pub message: String,
53 pub context: Option<serde_json::Value>,
54}
55
56impl PolicyPendingError {
57 pub const HTTP_ACCEPTED: u16 = 202;
58
59 pub fn new(context: Option<serde_json::Value>) -> Self {
60 Self {
61 http_status: Self::HTTP_ACCEPTED,
62 message: "Operation triggered a policy pending approval".to_string(),
63 context,
64 }
65 }
66}
67
68impl fmt::Display for PolicyPendingError {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 let error_json = serde_json::json!({
71 "httpStatus": self.http_status,
72 "message": self.message,
73 "context": self.context,
74 });
75 write!(
76 f,
77 "{}",
78 serde_json::to_string_pretty(&error_json).unwrap_or_default()
79 )
80 }
81}
82
83impl Error for PolicyPendingError {}
84
85impl From<PolicyPendingError> for DfnsError {
86 fn from(err: PolicyPendingError) -> Self {
87 Self::new(err.http_status, err.message, err.context)
88 }
89}
90
91impl From<ReqwestError> for DfnsError {
92 fn from(err: ReqwestError) -> Self {
93 Self::new(
94 err.status().map(|s| s.as_u16()).unwrap_or(500),
95 err.to_string(),
96 None,
97 )
98 }
99}
100
101impl From<ParseError> for DfnsError {
102 fn from(err: ParseError) -> Self {
103 Self::new(400, format!("URL parsing error: {}", err), None)
104 }
105}
106
107impl From<InvalidHeaderValue> for DfnsError {
108 fn from(err: InvalidHeaderValue) -> Self {
109 Self::new(400, format!("Invalid header value: {}", err), None)
110 }
111}
112
113impl From<serde_json::Error> for DfnsError {
114 fn from(err: serde_json::Error) -> Self {
115 Self::new(400, format!("JSON serialization error: {}", err), None)
116 }
117}