1use std::collections::BTreeMap;
8
9use salvo::http::StatusCode;
10use serde_json::{Value, json};
11
12pub type Result<T> = std::result::Result<T, Error>;
13
14#[derive(Debug, Default, Clone, PartialEq, Eq)]
17pub struct ValidationErrors(BTreeMap<String, Vec<String>>);
18
19impl ValidationErrors {
20 pub fn new() -> Self {
21 Self::default()
22 }
23
24 pub fn add(&mut self, field: impl Into<String>, message: impl Into<String>) {
25 self.0.entry(field.into()).or_default().push(message.into());
26 }
27
28 pub fn is_empty(&self) -> bool {
29 self.0.is_empty()
30 }
31
32 pub fn fields(&self) -> impl Iterator<Item = (&String, &Vec<String>)> {
33 self.0.iter()
34 }
35
36 pub fn field_names(&self) -> impl Iterator<Item = &str> {
37 self.0.keys().map(String::as_str)
38 }
39
40 pub fn has(&self, field: &str) -> bool {
41 self.0.contains_key(field)
42 }
43
44 pub fn merge(&mut self, other: Self) {
46 for (field, messages) in other.0 {
47 self.0.entry(field).or_default().extend(messages);
48 }
49 }
50
51 fn to_json(&self) -> Value {
52 json!(self.0)
53 }
54}
55
56impl FromIterator<(String, Vec<String>)> for ValidationErrors {
57 fn from_iter<I: IntoIterator<Item = (String, Vec<String>)>>(iter: I) -> Self {
58 Self(iter.into_iter().collect())
59 }
60}
61
62#[derive(Debug, thiserror::Error)]
63pub enum Error {
64 #[error("the given data was invalid")]
65 Validation(ValidationErrors),
66
67 #[error("{resource} `{id}` not found")]
68 NotFound { resource: &'static str, id: String },
69
70 #[error("unauthenticated")]
71 Unauthorized,
72
73 #[error("this action is forbidden")]
74 Forbidden,
75
76 #[error("{0}")]
77 Conflict(String),
78
79 #[error("too many requests")]
80 TooManyRequests,
81
82 #[error("{0}")]
83 BadRequest(String),
84
85 #[error("{message}")]
86 Http {
87 status: u16,
88 code: String,
89 message: String,
90 details: Option<Value>,
91 },
92
93 #[error(transparent)]
94 Internal(#[from] anyhow::Error),
95}
96
97impl Error {
98 pub fn not_found(resource: &'static str, id: impl std::fmt::Display) -> Self {
99 Self::NotFound {
100 resource,
101 id: id.to_string(),
102 }
103 }
104
105 pub fn internal(message: impl std::fmt::Display) -> Self {
108 Self::Internal(anyhow::anyhow!("{message}"))
109 }
110
111 pub fn status_code(&self) -> StatusCode {
112 match self {
113 Self::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
114 Self::NotFound { .. } => StatusCode::NOT_FOUND,
115 Self::Unauthorized => StatusCode::UNAUTHORIZED,
116 Self::Forbidden => StatusCode::FORBIDDEN,
117 Self::Conflict(_) => StatusCode::CONFLICT,
118 Self::TooManyRequests => StatusCode::TOO_MANY_REQUESTS,
119 Self::BadRequest(_) => StatusCode::BAD_REQUEST,
120 Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
121 Self::Http { status, .. } => {
122 StatusCode::from_u16(*status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
123 }
124 }
125 }
126
127 pub fn code(&self) -> &str {
130 match self {
131 Self::Validation(_) => "validation",
132 Self::NotFound { .. } => "not-found",
133 Self::Unauthorized => "unauthorized",
134 Self::Forbidden => "forbidden",
135 Self::Conflict(_) => "conflict",
136 Self::TooManyRequests => "too-many-requests",
137 Self::BadRequest(_) => "bad-request",
138 Self::Internal(_) => "internal",
139 Self::Http { code, .. } => code,
140 }
141 }
142
143 fn is_public(&self) -> bool {
146 !matches!(self, Self::Internal(_))
147 }
148
149 pub fn problem(&self) -> Value {
151 let mut problem = json!({
152 "type": format!("https://luxid.rs/errors/{}", self.code()),
153 "title": if self.is_public() { self.to_string() } else { "internal server error".to_owned() },
154 "status": self.status_code().as_u16(),
155 });
156
157 let map = problem.as_object_mut().expect("problem is an object");
158
159 match self {
160 Self::Validation(errors) => {
161 map.insert("errors".into(), errors.to_json());
162 }
163 Self::NotFound { resource, id } => {
164 map.insert("resource".into(), json!(resource));
165 map.insert("id".into(), json!(id));
166 }
167 Self::Http {
168 details: Some(details),
169 ..
170 } => {
171 map.insert("details".into(), details.clone());
172 }
173 _ => {}
174 }
175
176 problem
177 }
178}
179
180impl From<serde_json::Error> for Error {
181 fn from(err: serde_json::Error) -> Self {
182 Self::BadRequest(format!("malformed JSON: {err}"))
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 #[test]
191 fn maps_variants_to_status_codes() {
192 assert_eq!(Error::Unauthorized.status_code(), StatusCode::UNAUTHORIZED);
193 assert_eq!(
194 Error::not_found("User", 7).status_code(),
195 StatusCode::NOT_FOUND
196 );
197 assert_eq!(
198 Error::Validation(ValidationErrors::new()).status_code(),
199 StatusCode::UNPROCESSABLE_ENTITY
200 );
201 }
202
203 #[test]
204 fn validation_problem_carries_field_errors() {
205 let mut errors = ValidationErrors::new();
206 errors.add("email", "must be a valid email address");
207 errors.add("email", "is already taken");
208 errors.add("name", "is required");
209
210 let problem = Error::Validation(errors).problem();
211
212 assert_eq!(problem["status"], 422);
213 assert_eq!(problem["type"], "https://luxid.rs/errors/validation");
214 assert_eq!(problem["errors"]["email"][1], "is already taken");
215 assert_eq!(problem["errors"]["name"][0], "is required");
216 }
217
218 #[test]
219 fn the_internal_constructor_redacts_too() {
220 let problem = Error::internal("secret token abc123").problem();
221
222 assert_eq!(problem["status"], 500);
223 assert!(!problem.to_string().contains("abc123"));
224 }
225
226 #[test]
227 fn internal_errors_are_redacted() {
228 let err = Error::Internal(anyhow::anyhow!(
229 "connection string: postgres://user:hunter2@db"
230 ));
231 let problem = err.problem();
232
233 assert_eq!(problem["status"], 500);
234 assert_eq!(problem["title"], "internal server error");
235 assert!(!problem.to_string().contains("hunter2"));
236 }
237
238 #[test]
239 fn not_found_reports_the_resource() {
240 let problem = Error::not_found("User", 42).problem();
241 assert_eq!(problem["status"], 404);
242 assert_eq!(problem["resource"], "User");
243 assert_eq!(problem["id"], "42");
244 }
245}