1use serde_json::Value;
8
9#[derive(Debug, Clone, PartialEq, Eq, Default)]
11pub enum ErrorCondition {
12 StringTooShort { min_length: Option<u64> },
14 StringTooLong { max_length: Option<u64> },
16 GreaterThan { value: Option<i64> },
18 GreaterThanEqual { value: Option<i64> },
20 LessThan { value: Option<i64> },
22 LessThanEqual { value: Option<i64> },
24 Enum { values: Option<Vec<String>> },
26 StringPatternMismatch { pattern: Option<String> },
28 EmailFormat,
30 UuidFormat,
32 DatetimeFormat,
34 DateFormat,
36 FormatError,
38 TypeMismatch { expected_type: String },
40 Missing,
42 AdditionalProperties { field: String },
44 TooFewItems { min_items: Option<usize> },
46 TooManyItems,
48 #[default]
50 ValidationError,
51}
52
53impl ErrorCondition {
54 #[must_use]
56 pub fn from_schema_error(schema_path_str: &str, error_msg: &str) -> Self {
57 if schema_path_str.contains("minLength") {
58 Self::StringTooShort { min_length: None }
59 } else if schema_path_str.contains("maxLength") {
60 Self::StringTooLong { max_length: None }
61 } else if schema_path_str.contains("exclusiveMinimum")
62 || (error_msg.contains("less than or equal to") && error_msg.contains("minimum"))
63 {
64 Self::GreaterThan { value: None }
65 } else if schema_path_str.contains("minimum") || error_msg.contains("less than the minimum") {
66 Self::GreaterThanEqual { value: None }
67 } else if schema_path_str.contains("exclusiveMaximum")
68 || (error_msg.contains("greater than or equal to") && error_msg.contains("maximum"))
69 {
70 Self::LessThan { value: None }
71 } else if schema_path_str.contains("maximum") || error_msg.contains("greater than the maximum") {
72 Self::LessThanEqual { value: None }
73 } else if schema_path_str.contains("enum") || error_msg.contains("is not one of") {
74 Self::Enum { values: None }
75 } else if schema_path_str.contains("pattern") || error_msg.contains("does not match") {
76 Self::StringPatternMismatch { pattern: None }
77 } else if schema_path_str.contains("format") {
78 if error_msg.contains("email") {
79 Self::EmailFormat
80 } else if error_msg.contains("uuid") {
81 Self::UuidFormat
82 } else if error_msg.contains("date-time") {
83 Self::DatetimeFormat
84 } else if error_msg.contains("date") {
85 Self::DateFormat
86 } else {
87 Self::FormatError
88 }
89 } else if schema_path_str.contains("/type") {
90 Self::TypeMismatch {
91 expected_type: "unknown".to_string(),
92 }
93 } else if schema_path_str.ends_with("/required") {
94 Self::Missing
95 } else if schema_path_str.contains("/additionalProperties")
96 || error_msg.contains("Additional properties are not allowed")
97 {
98 Self::AdditionalProperties { field: String::new() }
99 } else if schema_path_str.contains("/minItems") {
100 Self::TooFewItems { min_items: None }
101 } else if schema_path_str.contains("/maxItems") {
102 Self::TooManyItems
103 } else {
104 Self::ValidationError
105 }
106 }
107
108 #[must_use]
110 pub const fn error_type(&self) -> &'static str {
111 match self {
112 Self::StringTooShort { .. } => "string_too_short",
113 Self::StringTooLong { .. } => "string_too_long",
114 Self::GreaterThan { .. } => "greater_than",
115 Self::GreaterThanEqual { .. } => "greater_than_equal",
116 Self::LessThan { .. } => "less_than",
117 Self::LessThanEqual { .. } => "less_than_equal",
118 Self::Enum { .. } => "enum",
119 Self::StringPatternMismatch { .. } | Self::EmailFormat => "string_pattern_mismatch",
120 Self::UuidFormat => "uuid_parsing",
121 Self::DatetimeFormat => "datetime_parsing",
122 Self::DateFormat => "date_parsing",
123 Self::FormatError => "format_error",
124 Self::TypeMismatch { .. } => "type_error",
125 Self::Missing => "missing",
126 Self::AdditionalProperties { .. } | Self::ValidationError => "validation_error",
127 Self::TooFewItems { .. } => "too_short",
128 Self::TooManyItems => "too_long",
129 }
130 }
131
132 #[must_use]
134 pub const fn default_message(&self) -> &'static str {
135 match self {
136 Self::StringTooShort { .. } => "String is too short",
137 Self::StringTooLong { .. } => "String is too long",
138 Self::GreaterThan { .. } => "Input should be greater than the minimum",
139 Self::GreaterThanEqual { .. } => "Input should be greater than or equal to the minimum",
140 Self::LessThan { .. } => "Input should be less than the maximum",
141 Self::LessThanEqual { .. } => "Input should be less than or equal to the maximum",
142 Self::Enum { .. } => "Input should be one of the allowed values",
143 Self::StringPatternMismatch { .. } => "String does not match expected pattern",
144 Self::EmailFormat => "String should match email pattern",
145 Self::UuidFormat => "Input should be a valid UUID",
146 Self::DatetimeFormat => "Input should be a valid datetime",
147 Self::DateFormat => "Input should be a valid date",
148 Self::FormatError => "Invalid format",
149 Self::TypeMismatch { .. } => "Invalid type",
150 Self::Missing => "Field required",
151 Self::AdditionalProperties { .. } => "Additional properties are not allowed",
152 Self::TooFewItems { .. } => "List should have at least N items after validation",
153 Self::TooManyItems => "List should have at most N items after validation",
154 Self::ValidationError => "Validation error",
155 }
156 }
157}
158
159pub struct ErrorMapper;
161
162impl ErrorMapper {
163 #[must_use]
168 #[allow(
169 clippy::too_many_lines,
170 clippy::option_if_let_else,
171 clippy::redundant_closure_for_method_calls,
172 clippy::uninlined_format_args
173 )]
174 pub fn map_error(
175 condition: &ErrorCondition,
176 schema: &Value,
177 schema_prop_path: &str,
178 generic_message: &str,
179 ) -> (String, String, Option<Value>) {
180 match condition {
181 ErrorCondition::StringTooShort { .. } => {
182 if let Some(min_len) = schema
183 .pointer(&format!("{}/minLength", schema_prop_path))
184 .and_then(|v| v.as_u64())
185 {
186 let ctx = serde_json::json!({"min_length": min_len});
187 (
188 "string_too_short".to_string(),
189 format!("String should have at least {} characters", min_len),
190 Some(ctx),
191 )
192 } else {
193 ("string_too_short".to_string(), "String is too short".to_string(), None)
194 }
195 }
196 ErrorCondition::StringTooLong { .. } => {
197 if let Some(max_len) = schema
198 .pointer(&format!("{}/maxLength", schema_prop_path))
199 .and_then(|v| v.as_u64())
200 {
201 let ctx = serde_json::json!({"max_length": max_len});
202 (
203 "string_too_long".to_string(),
204 format!("String should have at most {} characters", max_len),
205 Some(ctx),
206 )
207 } else {
208 ("string_too_long".to_string(), "String is too long".to_string(), None)
209 }
210 }
211 ErrorCondition::GreaterThan { .. } => {
212 if let Some(min_val) = schema
213 .pointer(&format!("{}/exclusiveMinimum", schema_prop_path))
214 .and_then(|v| v.as_i64())
215 {
216 let ctx = serde_json::json!({"gt": min_val});
217 (
218 "greater_than".to_string(),
219 format!("Input should be greater than {}", min_val),
220 Some(ctx),
221 )
222 } else {
223 (
224 "greater_than".to_string(),
225 "Input should be greater than the minimum".to_string(),
226 None,
227 )
228 }
229 }
230 ErrorCondition::GreaterThanEqual { .. } => {
231 if let Some(min_val) = schema
232 .pointer(&format!("{}/minimum", schema_prop_path))
233 .and_then(|v| v.as_i64())
234 {
235 let ctx = serde_json::json!({"ge": min_val});
236 (
237 "greater_than_equal".to_string(),
238 format!("Input should be greater than or equal to {}", min_val),
239 Some(ctx),
240 )
241 } else {
242 (
243 "greater_than_equal".to_string(),
244 "Input should be greater than or equal to the minimum".to_string(),
245 None,
246 )
247 }
248 }
249 ErrorCondition::LessThan { .. } => {
250 if let Some(max_val) = schema
251 .pointer(&format!("{}/exclusiveMaximum", schema_prop_path))
252 .and_then(|v| v.as_i64())
253 {
254 let ctx = serde_json::json!({"lt": max_val});
255 (
256 "less_than".to_string(),
257 format!("Input should be less than {}", max_val),
258 Some(ctx),
259 )
260 } else {
261 (
262 "less_than".to_string(),
263 "Input should be less than the maximum".to_string(),
264 None,
265 )
266 }
267 }
268 ErrorCondition::LessThanEqual { .. } => {
269 if let Some(max_val) = schema
270 .pointer(&format!("{}/maximum", schema_prop_path))
271 .and_then(|v| v.as_i64())
272 {
273 let ctx = serde_json::json!({"le": max_val});
274 (
275 "less_than_equal".to_string(),
276 format!("Input should be less than or equal to {}", max_val),
277 Some(ctx),
278 )
279 } else {
280 (
281 "less_than_equal".to_string(),
282 "Input should be less than or equal to the maximum".to_string(),
283 None,
284 )
285 }
286 }
287 ErrorCondition::Enum { .. } => {
288 if let Some(enum_values) = schema
289 .pointer(&format!("{}/enum", schema_prop_path))
290 .and_then(|v| v.as_array())
291 {
292 let values: Vec<String> = enum_values
293 .iter()
294 .filter_map(|v| v.as_str().map(|s| format!("'{}'", s)))
295 .collect();
296
297 let msg = if values.len() > 1 {
298 let last = values.last().unwrap();
299 let rest = &values[..values.len() - 1];
300 format!("Input should be {} or {}", rest.join(", "), last)
301 } else if !values.is_empty() {
302 format!("Input should be {}", values[0])
303 } else {
304 "Input should be one of the allowed values".to_string()
305 };
306
307 let expected_str = if values.len() > 1 {
308 let last = values.last().unwrap();
309 let rest = &values[..values.len() - 1];
310 format!("{} or {}", rest.join(", "), last)
311 } else if !values.is_empty() {
312 values[0].clone()
313 } else {
314 "allowed values".to_string()
315 };
316 let ctx = serde_json::json!({"expected": expected_str});
317 ("enum".to_string(), msg, Some(ctx))
318 } else {
319 (
320 "enum".to_string(),
321 "Input should be one of the allowed values".to_string(),
322 None,
323 )
324 }
325 }
326 ErrorCondition::StringPatternMismatch { .. } => {
327 if let Some(pattern) = schema
328 .pointer(&format!("{}/pattern", schema_prop_path))
329 .and_then(|v| v.as_str())
330 {
331 let ctx = serde_json::json!({"pattern": pattern});
332 let msg = format!("String should match pattern '{}'", pattern);
333 ("string_pattern_mismatch".to_string(), msg, Some(ctx))
334 } else {
335 (
336 "string_pattern_mismatch".to_string(),
337 "String does not match expected pattern".to_string(),
338 None,
339 )
340 }
341 }
342 ErrorCondition::EmailFormat => {
343 let email_pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$";
344 let ctx = serde_json::json!({"pattern": email_pattern});
345 (
346 "string_pattern_mismatch".to_string(),
347 format!("String should match pattern '{}'", email_pattern),
348 Some(ctx),
349 )
350 }
351 ErrorCondition::UuidFormat => (
352 "uuid_parsing".to_string(),
353 "Input should be a valid UUID".to_string(),
354 None,
355 ),
356 ErrorCondition::DatetimeFormat => (
357 "datetime_parsing".to_string(),
358 "Input should be a valid datetime".to_string(),
359 None,
360 ),
361 ErrorCondition::DateFormat => (
362 "date_parsing".to_string(),
363 "Input should be a valid date".to_string(),
364 None,
365 ),
366 ErrorCondition::FormatError => ("format_error".to_string(), generic_message.to_string(), None),
367 ErrorCondition::TypeMismatch { expected_type } => {
368 let (error_type, msg) = match expected_type.as_str() {
369 "integer" => (
370 "int_parsing".to_string(),
371 "Input should be a valid integer, unable to parse string as an integer".to_string(),
372 ),
373 "number" => (
374 "float_parsing".to_string(),
375 "Input should be a valid number, unable to parse string as a number".to_string(),
376 ),
377 "boolean" => (
378 "bool_parsing".to_string(),
379 "Input should be a valid boolean".to_string(),
380 ),
381 "string" => ("string_type".to_string(), "Input should be a valid string".to_string()),
382 _ => (
383 "type_error".to_string(),
384 format!("Input should be a valid {}", expected_type),
385 ),
386 };
387 (error_type, msg, None)
388 }
389 ErrorCondition::Missing => ("missing".to_string(), "Field required".to_string(), None),
390 ErrorCondition::AdditionalProperties { field } => {
391 let ctx = serde_json::json!({
392 "additional_properties": false,
393 "unexpected_field": field
394 });
395 (
396 "validation_error".to_string(),
397 "Additional properties are not allowed".to_string(),
398 Some(ctx),
399 )
400 }
401 ErrorCondition::TooFewItems { min_items } => {
402 let min = schema
403 .pointer(&format!("{}/minItems", schema_prop_path))
404 .and_then(|v| v.as_u64())
405 .or_else(|| min_items.map(|v| v as u64))
406 .unwrap_or(1);
407 let ctx = serde_json::json!({
408 "min_length": min
409 });
410 (
411 "too_short".to_string(),
412 format!("List should have at least {} item after validation", min),
413 Some(ctx),
414 )
415 }
416 ErrorCondition::TooManyItems => {
417 let max = schema
418 .pointer(&format!("{}/maxItems", schema_prop_path))
419 .and_then(|v| v.as_u64())
420 .unwrap_or(1);
421 let ctx = serde_json::json!({
422 "max_length": max
423 });
424 (
425 "too_long".to_string(),
426 format!("List should have at most {} items after validation", max),
427 Some(ctx),
428 )
429 }
430 ErrorCondition::ValidationError => ("validation_error".to_string(), generic_message.to_string(), None),
431 }
432 }
433}
434
435#[cfg(test)]
436mod tests {
437 use super::*;
438 use serde_json::json;
439
440 #[test]
441 fn test_string_too_short_detection() {
442 let condition = ErrorCondition::from_schema_error("some/path/minLength", "");
443 assert_eq!(condition, ErrorCondition::StringTooShort { min_length: None });
444 }
445
446 #[test]
447 fn test_string_too_long_detection() {
448 let condition = ErrorCondition::from_schema_error("some/path/maxLength", "");
449 assert_eq!(condition, ErrorCondition::StringTooLong { max_length: None });
450 }
451
452 #[test]
453 fn test_minimum_detection() {
454 let condition = ErrorCondition::from_schema_error("some/path/minimum", "");
455 assert_eq!(condition, ErrorCondition::GreaterThanEqual { value: None });
456 }
457
458 #[test]
459 fn test_exclusive_minimum_detection() {
460 let condition = ErrorCondition::from_schema_error("some/path/exclusiveMinimum", "");
461 assert_eq!(condition, ErrorCondition::GreaterThan { value: None });
462 }
463
464 #[test]
465 fn test_maximum_detection() {
466 let condition = ErrorCondition::from_schema_error("some/path/maximum", "");
467 assert_eq!(condition, ErrorCondition::LessThanEqual { value: None });
468 }
469
470 #[test]
471 fn test_exclusive_maximum_detection() {
472 let condition = ErrorCondition::from_schema_error("some/path/exclusiveMaximum", "");
473 assert_eq!(condition, ErrorCondition::LessThan { value: None });
474 }
475
476 #[test]
477 fn test_enum_detection() {
478 let condition = ErrorCondition::from_schema_error("some/path/enum", "");
479 assert_eq!(condition, ErrorCondition::Enum { values: None });
480 }
481
482 #[test]
483 fn test_pattern_detection() {
484 let condition = ErrorCondition::from_schema_error("some/path/pattern", "");
485 assert_eq!(condition, ErrorCondition::StringPatternMismatch { pattern: None });
486 }
487
488 #[test]
489 fn test_email_format_detection() {
490 let condition = ErrorCondition::from_schema_error("some/path/format", "email");
491 assert_eq!(condition, ErrorCondition::EmailFormat);
492 }
493
494 #[test]
495 fn test_uuid_format_detection() {
496 let condition = ErrorCondition::from_schema_error("some/path/format", "uuid");
497 assert_eq!(condition, ErrorCondition::UuidFormat);
498 }
499
500 #[test]
501 fn test_datetime_format_detection() {
502 let condition = ErrorCondition::from_schema_error("some/path/format", "date-time");
503 assert_eq!(condition, ErrorCondition::DatetimeFormat);
504 }
505
506 #[test]
507 fn test_date_format_detection() {
508 let condition = ErrorCondition::from_schema_error("some/path/format", "date");
509 assert_eq!(condition, ErrorCondition::DateFormat);
510 }
511
512 #[test]
513 fn test_type_error_detection() {
514 let condition = ErrorCondition::from_schema_error("some/path/type", "");
515 assert!(matches!(condition, ErrorCondition::TypeMismatch { .. }));
516 }
517
518 #[test]
519 fn test_missing_field_detection() {
520 let condition = ErrorCondition::from_schema_error("some/path/required", "");
521 assert_eq!(condition, ErrorCondition::Missing);
522 }
523
524 #[test]
525 fn test_additional_properties_detection() {
526 let condition = ErrorCondition::from_schema_error("some/path/additionalProperties", "");
527 assert!(matches!(condition, ErrorCondition::AdditionalProperties { .. }));
528 }
529
530 #[test]
531 fn test_min_items_detection() {
532 let condition = ErrorCondition::from_schema_error("some/path/minItems", "");
533 assert!(matches!(condition, ErrorCondition::TooFewItems { .. }));
534 }
535
536 #[test]
537 fn test_max_items_detection() {
538 let condition = ErrorCondition::from_schema_error("some/path/maxItems", "");
539 assert_eq!(condition, ErrorCondition::TooManyItems);
540 }
541
542 #[test]
543 fn test_error_type_codes() {
544 assert_eq!(
545 ErrorCondition::StringTooShort { min_length: None }.error_type(),
546 "string_too_short"
547 );
548 assert_eq!(
549 ErrorCondition::StringTooLong { max_length: None }.error_type(),
550 "string_too_long"
551 );
552 assert_eq!(ErrorCondition::GreaterThan { value: None }.error_type(), "greater_than");
553 assert_eq!(
554 ErrorCondition::GreaterThanEqual { value: None }.error_type(),
555 "greater_than_equal"
556 );
557 assert_eq!(ErrorCondition::LessThan { value: None }.error_type(), "less_than");
558 assert_eq!(
559 ErrorCondition::LessThanEqual { value: None }.error_type(),
560 "less_than_equal"
561 );
562 assert_eq!(ErrorCondition::Enum { values: None }.error_type(), "enum");
563 assert_eq!(
564 ErrorCondition::StringPatternMismatch { pattern: None }.error_type(),
565 "string_pattern_mismatch"
566 );
567 assert_eq!(ErrorCondition::EmailFormat.error_type(), "string_pattern_mismatch");
568 assert_eq!(ErrorCondition::UuidFormat.error_type(), "uuid_parsing");
569 assert_eq!(ErrorCondition::DatetimeFormat.error_type(), "datetime_parsing");
570 assert_eq!(ErrorCondition::DateFormat.error_type(), "date_parsing");
571 assert_eq!(ErrorCondition::FormatError.error_type(), "format_error");
572 assert_eq!(
573 ErrorCondition::TypeMismatch {
574 expected_type: "integer".to_string()
575 }
576 .error_type(),
577 "type_error"
578 );
579 assert_eq!(ErrorCondition::Missing.error_type(), "missing");
580 assert_eq!(
581 ErrorCondition::AdditionalProperties {
582 field: "extra".to_string()
583 }
584 .error_type(),
585 "validation_error"
586 );
587 assert_eq!(
588 ErrorCondition::TooFewItems { min_items: None }.error_type(),
589 "too_short"
590 );
591 assert_eq!(ErrorCondition::TooManyItems.error_type(), "too_long");
592 }
593
594 #[test]
595 fn test_mapper_string_length_constraints() {
596 let schema = json!({
597 "properties": {
598 "name": {
599 "type": "string",
600 "minLength": 5,
601 "maxLength": 20
602 }
603 }
604 });
605
606 let condition = ErrorCondition::StringTooShort { min_length: None };
607 let (error_type, msg, ctx_result) = ErrorMapper::map_error(&condition, &schema, "/properties/name", "");
608 assert_eq!(error_type, "string_too_short");
609 assert_eq!(msg, "String should have at least 5 characters");
610 assert_eq!(ctx_result, Some(json!({"min_length": 5})));
611 }
612
613 #[test]
614 fn test_mapper_numeric_constraints() {
615 let schema = json!({
616 "properties": {
617 "age": {
618 "type": "integer",
619 "minimum": 0,
620 "maximum": 150,
621 "exclusiveMinimum": -1,
622 "exclusiveMaximum": 151
623 }
624 }
625 });
626
627 let condition = ErrorCondition::GreaterThanEqual { value: None };
628 let (error_type, msg, ctx) = ErrorMapper::map_error(&condition, &schema, "/properties/age", "");
629 assert_eq!(error_type, "greater_than_equal");
630 assert_eq!(msg, "Input should be greater than or equal to 0");
631 assert_eq!(ctx, Some(json!({"ge": 0})));
632 }
633
634 #[test]
635 fn test_mapper_enum() {
636 let schema = json!({
637 "properties": {
638 "status": {
639 "type": "string",
640 "enum": ["active", "inactive", "pending"]
641 }
642 }
643 });
644
645 let condition = ErrorCondition::Enum { values: None };
646 let (error_type, msg, _ctx) = ErrorMapper::map_error(&condition, &schema, "/properties/status", "");
647 assert_eq!(error_type, "enum");
648 assert!(msg.contains("'active'"));
649 assert!(msg.contains("'inactive'"));
650 assert!(msg.contains("'pending'"));
651 }
652
653 #[test]
654 fn test_mapper_type_mismatch() {
655 let schema = json!({
656 "properties": {
657 "count": { "type": "integer" }
658 }
659 });
660
661 let condition = ErrorCondition::TypeMismatch {
662 expected_type: "integer".to_string(),
663 };
664 let (error_type, msg, _) = ErrorMapper::map_error(&condition, &schema, "/properties/count", "");
665 assert_eq!(error_type, "int_parsing");
666 assert!(msg.contains("integer"));
667 }
668
669 #[test]
670 fn test_mapper_email_format() {
671 let schema = json!({});
672
673 let condition = ErrorCondition::EmailFormat;
674 let (error_type, msg, ctx) = ErrorMapper::map_error(&condition, &schema, "", "");
675 assert_eq!(error_type, "string_pattern_mismatch");
676 assert!(msg.contains('@'));
677 assert!(ctx.is_some());
678 }
679
680 #[test]
681 fn test_mapper_uuid_format() {
682 let schema = json!({});
683
684 let condition = ErrorCondition::UuidFormat;
685 let (error_type, msg, _) = ErrorMapper::map_error(&condition, &schema, "", "");
686 assert_eq!(error_type, "uuid_parsing");
687 assert_eq!(msg, "Input should be a valid UUID");
688 }
689
690 #[test]
691 fn test_mapper_additional_properties() {
692 let schema = json!({});
693
694 let condition = ErrorCondition::AdditionalProperties {
695 field: "extra_field".to_string(),
696 };
697 let (error_type, msg, ctx) = ErrorMapper::map_error(&condition, &schema, "", "");
698 assert_eq!(error_type, "validation_error");
699 assert_eq!(msg, "Additional properties are not allowed");
700 assert_eq!(
701 ctx,
702 Some(json!({
703 "additional_properties": false,
704 "unexpected_field": "extra_field"
705 }))
706 );
707 }
708}