1use std::fmt;
2use std::sync::Arc;
3use thiserror::Error;
4
5#[derive(Debug, Clone, PartialEq, Eq, Error)]
11#[non_exhaustive]
12pub enum ConfigValidationError {
13 #[error(
14 "aggregator config requires at least one completion bound (size, timeout, predicate, or interval)"
15 )]
16 AggregatorMissingCompletionBound,
17
18 #[error("aggregator requires at least one of max_buckets, completionTimeout, or bucket_ttl")]
23 AggregatorMissingMemoryBound,
24
25 #[error(
32 "aggregator Timeout completion requires bucket_ttl (memory-release bound for the timeout-task cap fallback)"
33 )]
34 AggregatorTimeoutRequiresTtl,
35
36 #[error("throttler max_requests must be > 0")]
37 ThrottlerMaxRequestsZero,
38
39 #[error("loop step must specify either 'count' or 'while', not both")]
40 LoopConflictingCountAndWhile,
41
42 #[error("on_exceptions clause cannot set both steps and handled_by (delegation is exclusive)")]
43 OnExceptionStepsHandledByConflict,
44
45 #[error("loop step must specify either 'count' or 'while'")]
46 LoopMissingCountOrWhile,
47
48 #[error("SQL use_message_body_for_sql requires allow_dynamic_query=true")]
49 SqlDynamicQueryWithoutAllowDynamic,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Error)]
58#[non_exhaustive]
59pub enum EndpointUriError {
60 #[error(
62 "endpoint URI parameter `{key}` duplicates a key already present in the base URI query"
63 )]
64 DuplicateKey { key: String },
65
66 #[error("endpoint URI is missing a scheme (expected `scheme:path`)")]
68 MissingScheme,
69
70 #[error("endpoint URI query contains a pair with an empty key")]
72 EmptyQueryKey,
73
74 #[error("endpoint URI parameter key `{key}` is empty or contains a reserved character")]
76 InvalidParamKey { key: String },
77}
78
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86#[non_exhaustive]
87pub enum ExpressionErrorClass {
88 Runtime,
90 Arithmetic,
92 TypeMismatch,
94 FunctionNotFound,
96 Limit,
98 Timeout,
100 Conversion,
102 Parse,
104}
105
106impl ExpressionErrorClass {
107 pub fn as_str(&self) -> &'static str {
109 match self {
110 Self::Runtime => "runtime",
111 Self::Arithmetic => "arithmetic",
112 Self::TypeMismatch => "type-mismatch",
113 Self::FunctionNotFound => "function-not-found",
114 Self::Limit => "limit",
115 Self::Timeout => "timeout",
116 Self::Conversion => "conversion",
117 Self::Parse => "parse",
118 }
119 }
120}
121
122impl fmt::Display for ExpressionErrorClass {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 f.write_str(self.as_str())
125 }
126}
127
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub struct ErrorPosition {
132 pub line: u32,
134 pub column: u32,
136}
137
138impl fmt::Display for ErrorPosition {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 write!(f, "{}:{}", self.line, self.column)
141 }
142}
143
144#[derive(Clone, Debug, PartialEq, Eq)]
149pub struct ConversionDetail {
150 pub source_type: String,
152 pub target: String,
154}
155
156fn expression_position_suffix(position: &Option<ErrorPosition>) -> String {
158 match position {
159 Some(pos) => format!(" at {pos}"),
160 None => String::new(),
161 }
162}
163
164fn expression_conversion_suffix(conversion: &Option<ConversionDetail>) -> String {
167 match conversion {
168 Some(detail) => format!(
169 " while converting {} to {}",
170 detail.source_type, detail.target
171 ),
172 None => String::new(),
173 }
174}
175
176#[derive(Debug)]
228pub struct OpaqueErrorSource(Arc<dyn std::error::Error + Send + Sync>);
229
230impl OpaqueErrorSource {
231 pub fn new(source: Arc<dyn std::error::Error + Send + Sync>) -> Self {
233 Self(source)
234 }
235
236 fn clone_handle(&self) -> Self {
240 Self(Arc::clone(&self.0))
241 }
242}
243
244impl fmt::Display for OpaqueErrorSource {
245 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246 self.0.fmt(f)
247 }
248}
249
250impl std::error::Error for OpaqueErrorSource {
251 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
252 Some(self.0.as_ref())
255 }
256}
257
258#[derive(Clone, PartialEq, Eq)]
276pub struct RedactedJson(serde_json::Value);
277
278impl RedactedJson {
279 pub fn new(value: serde_json::Value) -> Self {
281 Self(value)
282 }
283
284 pub fn as_value(&self) -> &serde_json::Value {
287 &self.0
288 }
289}
290
291impl fmt::Debug for RedactedJson {
292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293 f.write_str("[redacted]")
294 }
295}
296
297#[derive(Debug, Error)]
299#[non_exhaustive]
300pub enum CamelError {
301 #[error("Component not found: {0}")]
302 ComponentNotFound(String),
303
304 #[error("Endpoint creation failed: {0}")]
305 EndpointCreationFailed(String),
306
307 #[error("Endpoint creation failed: {0}")]
310 EndpointCreationFailedWithSource(String, #[source] OpaqueErrorSource),
311
312 #[error("Processor error: {0}")]
313 ProcessorError(String),
314
315 #[error("Processor error: {0}")]
318 ProcessorErrorWithSource(String, #[source] Arc<dyn std::error::Error + Send + Sync>),
319
320 #[error("Type conversion failed: {0}")]
321 TypeConversionFailed(String),
322
323 #[error("Invalid URI: {0}")]
324 InvalidUri(String),
325
326 #[error("Channel closed")]
327 ChannelClosed,
328
329 #[error("Route error: {0}")]
330 RouteError(String),
331
332 #[error("IO error: {0}")]
333 Io(String),
334
335 #[error("Dead letter channel failed: {0}")]
336 DeadLetterChannelFailed(String),
337
338 #[error("Circuit breaker open: {0}")]
339 CircuitOpen(String),
340
341 #[error("HTTP {method} {url} failed: {status_code} {status_text}")]
342 HttpOperationFailed {
343 method: String,
344 url: String,
345 status_code: u16,
346 status_text: String,
347 response_body: Option<String>,
348 },
349
350 #[error("Consumer stopping: semaphore closed during call")]
354 ConsumerStopping,
355
356 #[error("Configuration error: {0}")]
357 Config(String),
358
359 #[error("Configuration validation error: {0}")]
363 ConfigValidation(ConfigValidationError),
364
365 #[error("Body stream has already been consumed")]
366 AlreadyConsumed,
367
368 #[error("Stream size exceeded limit: {0}")]
369 StreamLimitExceeded(usize),
370
371 #[error("Unauthenticated: {0}")]
372 Unauthenticated(String),
373
374 #[error("Unauthorized: {0}")]
375 Unauthorized(String),
376
377 #[error("Auth provider unavailable: {0}")]
381 AuthProviderUnavailable(String),
382
383 #[error("Validation failed: {0}")]
384 ValidationError(String),
385
386 #[error("Template reload failed: {0}")]
387 TemplateReload(String),
388
389 #[error("Endpoint URI error: {0}")]
393 EndpointUri(EndpointUriError),
394
395 #[error("Unsupported media type: consumed {consumed}, declared {declared}")]
398 UnsupportedMediaType { consumed: String, declared: String },
399
400 #[error("Not acceptable: accept {accept}, produced {produced}")]
403 NotAcceptable { accept: String, produced: String },
404
405 #[error(
409 "expression failed: {class} in {language} `{verb}` step `{step_id}` (route `{route_id}`){}{}",
410 expression_position_suffix(.position),
411 expression_conversion_suffix(.conversion),
412 )]
413 ExpressionFailed {
414 language: String,
416 route_id: String,
418 step_id: String,
420 verb: String,
422 class: ExpressionErrorClass,
424 position: Option<ErrorPosition>,
426 conversion: Option<ConversionDetail>,
428 #[source]
432 cause: Option<Box<CamelError>>,
433 },
434
435 #[error("business error {code} ({kind})")]
450 Business {
451 code: String,
453 kind: String,
456 message: String,
458 data: Option<RedactedJson>,
460 },
461
462 #[error(transparent)]
466 Transaction(#[from] crate::transaction::TransactionError),
467}
468
469impl Clone for CamelError {
475 fn clone(&self) -> Self {
476 match self {
477 Self::ComponentNotFound(msg) => Self::ComponentNotFound(msg.clone()),
478 Self::EndpointCreationFailed(msg) => Self::EndpointCreationFailed(msg.clone()),
479 Self::EndpointCreationFailedWithSource(msg, source) => {
480 Self::EndpointCreationFailedWithSource(msg.clone(), source.clone_handle())
481 }
482 Self::ProcessorError(msg) => Self::ProcessorError(msg.clone()),
483 Self::ProcessorErrorWithSource(msg, source) => {
484 Self::ProcessorErrorWithSource(msg.clone(), Arc::clone(source))
485 }
486 Self::TypeConversionFailed(msg) => Self::TypeConversionFailed(msg.clone()),
487 Self::InvalidUri(msg) => Self::InvalidUri(msg.clone()),
488 Self::ChannelClosed => Self::ChannelClosed,
489 Self::RouteError(msg) => Self::RouteError(msg.clone()),
490 Self::Io(msg) => Self::Io(msg.clone()),
491 Self::DeadLetterChannelFailed(msg) => Self::DeadLetterChannelFailed(msg.clone()),
492 Self::CircuitOpen(msg) => Self::CircuitOpen(msg.clone()),
493 Self::HttpOperationFailed {
494 method,
495 url,
496 status_code,
497 status_text,
498 response_body,
499 } => Self::HttpOperationFailed {
500 method: method.clone(),
501 url: url.clone(),
502 status_code: *status_code,
503 status_text: status_text.clone(),
504 response_body: response_body.clone(),
505 },
506 Self::ConsumerStopping => Self::ConsumerStopping,
507 Self::Config(msg) => Self::Config(msg.clone()),
508 Self::ConfigValidation(e) => Self::ConfigValidation(e.clone()),
509 Self::AlreadyConsumed => Self::AlreadyConsumed,
510 Self::StreamLimitExceeded(limit) => Self::StreamLimitExceeded(*limit),
511 Self::Unauthenticated(msg) => Self::Unauthenticated(msg.clone()),
512 Self::Unauthorized(msg) => Self::Unauthorized(msg.clone()),
513 Self::AuthProviderUnavailable(msg) => Self::AuthProviderUnavailable(msg.clone()),
514 Self::ValidationError(msg) => Self::ValidationError(msg.clone()),
515 Self::TemplateReload(msg) => Self::TemplateReload(msg.clone()),
516 Self::EndpointUri(e) => Self::EndpointUri(e.clone()),
517 Self::UnsupportedMediaType { consumed, declared } => Self::UnsupportedMediaType {
518 consumed: consumed.clone(),
519 declared: declared.clone(),
520 },
521 Self::NotAcceptable { accept, produced } => Self::NotAcceptable {
522 accept: accept.clone(),
523 produced: produced.clone(),
524 },
525 Self::ExpressionFailed {
526 language,
527 route_id,
528 step_id,
529 verb,
530 class,
531 position,
532 conversion,
533 cause,
534 } => Self::ExpressionFailed {
535 language: language.clone(),
536 route_id: route_id.clone(),
537 step_id: step_id.clone(),
538 verb: verb.clone(),
539 class: *class,
540 position: *position,
541 conversion: conversion.clone(),
542 cause: cause.clone(),
543 },
544 Self::Business {
545 code,
546 kind,
547 message,
548 data,
549 } => Self::Business {
550 code: code.clone(),
551 kind: kind.clone(),
552 message: message.clone(),
553 data: data.clone(),
554 },
555 Self::Transaction(e) => Self::Transaction(e.clone()),
556 }
557 }
558}
559
560pub const CIRCUIT_OPEN: &str = "circuit_open";
566
567impl CamelError {
568 pub fn classify(&self) -> &'static str {
569 #[allow(unreachable_patterns)]
570 match self {
571 Self::ComponentNotFound(_) => "component",
572 Self::EndpointCreationFailed(_)
573 | Self::EndpointCreationFailedWithSource(_, _)
574 | Self::InvalidUri(_)
575 | Self::EndpointUri(_) => "endpoint",
576 Self::ProcessorError(_)
577 | Self::ProcessorErrorWithSource(_, _)
578 | Self::AuthProviderUnavailable(_) => "processor",
579 Self::TypeConversionFailed(_) | Self::AlreadyConsumed => "type_conversion",
580 Self::Io(_) => "io",
581 Self::RouteError(_) => "route",
582 Self::CircuitOpen(_) => CIRCUIT_OPEN,
583 Self::HttpOperationFailed { .. } => "http",
584 Self::Config(_) | Self::ConfigValidation(_) => "config",
585 Self::DeadLetterChannelFailed(_) => "dead_letter",
586 Self::ConsumerStopping => "consumer_stop",
587 Self::StreamLimitExceeded(_) => "stream",
588 Self::ChannelClosed => "channel",
589 Self::Unauthenticated(_) => "unauthenticated",
590 Self::Unauthorized(_) => "unauthorized",
591 Self::ValidationError(_) => "validation",
592 Self::TemplateReload(_) => "template",
593 Self::UnsupportedMediaType { .. } => "unsupported_media_type",
594 Self::NotAcceptable { .. } => "not_acceptable",
595 Self::Business { .. } => "business",
596 Self::Transaction(_) => "transaction",
597 _ => "unknown",
598 }
599 }
600
601 pub fn variant_name(&self) -> &'static str {
613 match self {
614 Self::ComponentNotFound(_) => "ComponentNotFound",
615 Self::EndpointCreationFailed(_) => "EndpointCreationFailed",
616 Self::EndpointCreationFailedWithSource(_, _) => "EndpointCreationFailed",
617 Self::ProcessorError(_) => "ProcessorError",
618 Self::ProcessorErrorWithSource(_, _) => "ProcessorError",
619 Self::AuthProviderUnavailable(_) => "ProcessorError",
620 Self::TypeConversionFailed(_) => "TypeConversionFailed",
621 Self::InvalidUri(_) => "InvalidUri",
622 Self::ChannelClosed => "ChannelClosed",
623 Self::RouteError(_) => "RouteError",
624 Self::Io(_) => "Io",
625 Self::DeadLetterChannelFailed(_) => "DeadLetterChannelFailed",
626 Self::CircuitOpen(_) => "CircuitOpen",
627 Self::HttpOperationFailed { .. } => "HttpOperationFailed",
628 Self::ConsumerStopping => "ConsumerStopping",
629 Self::Config(_) => "Config",
630 Self::ConfigValidation(_) => "ConfigValidation",
631 Self::AlreadyConsumed => "AlreadyConsumed",
632 Self::StreamLimitExceeded(_) => "StreamLimitExceeded",
633 Self::Unauthenticated(_) => "Unauthenticated",
634 Self::Unauthorized(_) => "Unauthorized",
635 Self::ValidationError(_) => "ValidationError",
636 Self::TemplateReload(_) => "TemplateReload",
637 Self::EndpointUri(_) => "EndpointUri",
638 Self::UnsupportedMediaType { .. } => "UnsupportedMediaType",
639 Self::NotAcceptable { .. } => "NotAcceptable",
640 Self::ExpressionFailed { .. } => "ExpressionFailed",
641 Self::Business { .. } => "Business",
642 Self::Transaction(_) => "Transaction",
643 }
644 }
645}
646
647impl From<std::io::Error> for CamelError {
648 fn from(err: std::io::Error) -> Self {
649 CamelError::Io(err.to_string())
650 }
651}
652
653impl From<crate::template::TemplateError> for CamelError {
654 fn from(err: crate::template::TemplateError) -> Self {
655 CamelError::Config(err.to_string())
656 }
657}
658
659impl From<ConfigValidationError> for CamelError {
660 fn from(e: ConfigValidationError) -> Self {
661 CamelError::ConfigValidation(e)
662 }
663}
664
665impl From<EndpointUriError> for CamelError {
666 fn from(e: EndpointUriError) -> Self {
667 CamelError::EndpointUri(e)
668 }
669}
670
671pub type BoxError = std::boxed::Box<dyn std::error::Error + Send + Sync + 'static>;
673
674fn source_chain_contains_elapsed(err: &(dyn std::error::Error + 'static)) -> bool {
680 let mut current = Some(err);
681 while let Some(source) = current {
682 if source
683 .downcast_ref::<tower::timeout::error::Elapsed>()
684 .is_some()
685 {
686 return true;
687 }
688 current = std::error::Error::source(source);
689 }
690 false
691}
692
693impl From<BoxError> for CamelError {
769 fn from(err: BoxError) -> Self {
770 match err.downcast::<CamelError>() {
773 Ok(camel_error) => *camel_error,
774 Err(err) => {
775 let message = if source_chain_contains_elapsed(err.as_ref()) {
776 "middleware timeout elapsed"
777 } else {
778 "middleware error"
779 };
780 CamelError::ProcessorErrorWithSource(
781 message.to_string(),
782 Arc::new(OpaqueErrorSource::new(Arc::from(err))),
783 )
784 }
785 }
786 }
787}
788
789#[cfg(test)]
790mod tests {
791 use super::*;
792 use std::error::Error as _;
795
796 #[derive(Debug)]
798 struct SampleSource;
799
800 impl fmt::Display for SampleSource {
801 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802 f.write_str("sample source")
803 }
804 }
805
806 impl std::error::Error for SampleSource {}
807
808 #[derive(Debug)]
813 struct ElapsedSourcedError(tower::timeout::error::Elapsed);
814
815 impl fmt::Display for ElapsedSourcedError {
816 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
817 f.write_str("wrapped middleware failure")
818 }
819 }
820
821 impl std::error::Error for ElapsedSourcedError {
822 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
823 Some(&self.0)
824 }
825 }
826
827 #[test]
828 fn boxed_camel_error_passthrough_unchanged() {
829 let boxed: Box<dyn std::error::Error + Send + Sync> =
830 Box::<dyn std::error::Error + Send + Sync>::from(CamelError::InvalidUri(
831 "u".to_string(),
832 ));
833 let err = CamelError::from(boxed);
834 match err {
835 CamelError::InvalidUri(uri) => assert_eq!(uri, "u"),
836 other => panic!("expected InvalidUri passthrough, got {other:?}"),
837 }
838 }
839
840 fn assert_elapsed_within_source_hops(err: &CamelError, max_hops: usize) {
848 let mut current = err.source();
849 for _ in 0..max_hops {
850 let Some(node) = current else { break };
851 if node
852 .downcast_ref::<tower::timeout::error::Elapsed>()
853 .is_some()
854 {
855 return;
856 }
857 current = node.source();
858 }
859 panic!("source chain does not reach tower Elapsed within {max_hops} hops: {err:?}");
860 }
861
862 #[test]
863 fn timeout_error_classified_through_source_chain() {
864 let boxed: Box<dyn std::error::Error + Send + Sync> =
865 Box::new(ElapsedSourcedError(tower::timeout::error::Elapsed::new()));
866 let err = CamelError::from(boxed);
867 assert!(
868 err.to_string().contains("middleware timeout elapsed"),
869 "unexpected display: {err}"
870 );
871 assert_elapsed_within_source_hops(&err, 3);
872 }
873
874 #[test]
875 fn bare_elapsed_root_error_classified_as_timeout() {
876 let boxed: Box<dyn std::error::Error + Send + Sync> =
880 Box::new(tower::timeout::error::Elapsed::new());
881 let err = CamelError::from(boxed);
882 assert!(
883 err.to_string().contains("middleware timeout elapsed"),
884 "unexpected display: {err}"
885 );
886 assert_elapsed_within_source_hops(&err, 3);
887 }
888
889 #[test]
890 #[allow(clippy::io_other_error)]
891 fn plain_box_error_preserves_source() {
892 let boxed: Box<dyn std::error::Error + Send + Sync> =
893 Box::new(std::io::Error::new(std::io::ErrorKind::Other, "boom"));
894 let err = CamelError::from(boxed);
895 match &err {
896 CamelError::ProcessorErrorWithSource(message, _) => {
897 assert!(
898 message.contains("middleware error"),
899 "unexpected message: {message}"
900 );
901 }
902 other => panic!("expected ProcessorErrorWithSource, got {other:?}"),
903 }
904 let source = err
905 .source()
906 .expect("ProcessorErrorWithSource carries a source");
907 assert_eq!(source.to_string(), "boom");
908 }
909
910 fn all_error_samples() -> Vec<CamelError> {
911 vec![
912 CamelError::ComponentNotFound("x".to_string()),
913 CamelError::EndpointCreationFailed("x".to_string()),
914 CamelError::EndpointCreationFailedWithSource(
915 "x".to_string(),
916 OpaqueErrorSource::new(Arc::new(SampleSource)),
917 ),
918 CamelError::ProcessorError("x".to_string()),
919 CamelError::ProcessorErrorWithSource(
920 "x".to_string(),
921 Arc::new(std::io::Error::other("inner")),
922 ),
923 CamelError::TypeConversionFailed("x".to_string()),
924 CamelError::InvalidUri("x".to_string()),
925 CamelError::ChannelClosed,
926 CamelError::RouteError("x".to_string()),
927 CamelError::Io("x".to_string()),
928 CamelError::DeadLetterChannelFailed("x".to_string()),
929 CamelError::CircuitOpen("x".to_string()),
930 CamelError::HttpOperationFailed {
931 method: "GET".to_string(),
932 url: "https://example.com".to_string(),
933 status_code: 500,
934 status_text: "Internal Server Error".to_string(),
935 response_body: Some("error".to_string()),
936 },
937 CamelError::ConsumerStopping,
938 CamelError::Config("x".to_string()),
939 CamelError::ConfigValidation(ConfigValidationError::ThrottlerMaxRequestsZero),
940 CamelError::AlreadyConsumed,
941 CamelError::StreamLimitExceeded(42),
942 CamelError::Unauthenticated("token expired".to_string()),
943 CamelError::Unauthorized("missing admin role".to_string()),
944 CamelError::AuthProviderUnavailable("jwks down".to_string()),
945 CamelError::ValidationError("body does not match schema".to_string()),
946 CamelError::TemplateReload("reload failed".to_string()),
947 CamelError::EndpointUri(EndpointUriError::MissingScheme),
948 CamelError::UnsupportedMediaType {
949 consumed: "text/plain".to_string(),
950 declared: "application/json".to_string(),
951 },
952 CamelError::NotAcceptable {
953 accept: "application/xml".to_string(),
954 produced: "application/json".to_string(),
955 },
956 ]
957 }
958
959 #[test]
960 fn test_http_operation_failed_display() {
961 let err = CamelError::HttpOperationFailed {
962 method: "GET".to_string(),
963 url: "https://example.com/test".to_string(),
964 status_code: 404,
965 status_text: "Not Found".to_string(),
966 response_body: Some("page not found".to_string()),
967 };
968 let msg = format!("{err}");
969 assert!(msg.contains("404"));
970 assert!(msg.contains("Not Found"));
971 }
972
973 #[test]
974 fn test_http_operation_failed_clone() {
975 let err = CamelError::HttpOperationFailed {
976 method: "POST".to_string(),
977 url: "https://api.example.com/users".to_string(),
978 status_code: 500,
979 status_text: "Internal Server Error".to_string(),
980 response_body: None,
981 };
982 let cloned = err.clone();
983 assert!(matches!(
984 cloned,
985 CamelError::HttpOperationFailed {
986 status_code: 500,
987 ..
988 }
989 ));
990 }
991
992 #[test]
993 fn test_classify_maps_all_variants() {
994 assert_eq!(
995 CamelError::ComponentNotFound("x".to_string()).classify(),
996 "component"
997 );
998 assert_eq!(
999 CamelError::EndpointCreationFailed("x".to_string()).classify(),
1000 "endpoint"
1001 );
1002 assert_eq!(
1003 CamelError::ProcessorError("x".to_string()).classify(),
1004 "processor"
1005 );
1006 assert_eq!(
1007 CamelError::TypeConversionFailed("x".to_string()).classify(),
1008 "type_conversion"
1009 );
1010 assert_eq!(
1011 CamelError::InvalidUri("x".to_string()).classify(),
1012 "endpoint"
1013 );
1014 assert_eq!(CamelError::ChannelClosed.classify(), "channel");
1015 assert_eq!(CamelError::RouteError("x".to_string()).classify(), "route");
1016 assert_eq!(CamelError::Io("x".to_string()).classify(), "io");
1017 assert_eq!(
1018 CamelError::DeadLetterChannelFailed("x".to_string()).classify(),
1019 "dead_letter"
1020 );
1021 assert_eq!(
1022 CamelError::CircuitOpen("x".to_string()).classify(),
1023 "circuit_open"
1024 );
1025 assert_eq!(
1026 CamelError::HttpOperationFailed {
1027 method: "GET".to_string(),
1028 url: "https://example.com".to_string(),
1029 status_code: 500,
1030 status_text: "Internal Server Error".to_string(),
1031 response_body: None,
1032 }
1033 .classify(),
1034 "http"
1035 );
1036 assert_eq!(CamelError::Config("x".to_string()).classify(), "config");
1037 assert_eq!(
1038 CamelError::ConfigValidation(ConfigValidationError::ThrottlerMaxRequestsZero)
1039 .classify(),
1040 "config"
1041 );
1042 assert_eq!(CamelError::AlreadyConsumed.classify(), "type_conversion");
1043 assert_eq!(CamelError::StreamLimitExceeded(42).classify(), "stream");
1044 assert_eq!(
1045 CamelError::ValidationError("bad".to_string()).classify(),
1046 "validation"
1047 );
1048 }
1049
1050 #[test]
1051 fn test_classify_output_is_ascii_and_short() {
1052 for error in all_error_samples() {
1053 let class = error.classify();
1054 assert!(class.is_ascii());
1055 assert!(class.len() <= 22, "class too long: {class}");
1057 }
1058 }
1059
1060 #[test]
1061 fn test_auth_variants_classify() {
1062 assert_eq!(
1063 CamelError::Unauthenticated("x".to_string()).classify(),
1064 "unauthenticated"
1065 );
1066 assert_eq!(
1067 CamelError::Unauthorized("x".to_string()).classify(),
1068 "unauthorized"
1069 );
1070 }
1071
1072 #[test]
1073 fn test_validation_error_classify() {
1074 assert_eq!(
1075 CamelError::ValidationError("bad".to_string()).classify(),
1076 "validation"
1077 );
1078 }
1079
1080 #[test]
1081 fn template_reload_classifies_as_template() {
1082 let err = CamelError::TemplateReload("boom".into());
1083 assert_eq!(err.classify(), "template");
1084 }
1085
1086 #[test]
1087 fn template_reload_variant_name() {
1088 let err = CamelError::TemplateReload("boom".into());
1089 assert_eq!(err.variant_name(), "TemplateReload");
1090 }
1091
1092 #[test]
1093 fn test_auth_variants_are_clone() {
1094 let err = CamelError::Unauthenticated("test".to_string());
1095 let cloned = err.clone();
1096 assert!(matches!(cloned, CamelError::Unauthenticated(_)));
1097
1098 let err2 = CamelError::Unauthorized("test".to_string());
1099 let cloned2 = err2.clone();
1100 assert!(matches!(cloned2, CamelError::Unauthorized(_)));
1101 }
1102
1103 #[test]
1104 fn classification_unchanged_for_callers() {
1105 assert_eq!(
1110 CamelError::CircuitOpen("breaker open".into()).classify(),
1111 "circuit_open"
1112 );
1113 }
1114
1115 #[test]
1116 fn auth_provider_unavailable_display_carries_detail() {
1117 let err = CamelError::AuthProviderUnavailable("conn refused".into());
1118 let msg = err.to_string();
1119 assert!(msg.contains("conn refused"));
1120 assert!(
1121 msg.starts_with("Auth provider unavailable"),
1122 "display should start with 'Auth provider unavailable', got: {msg}"
1123 );
1124 }
1125
1126 #[test]
1127 fn classify_negotiation_errors() {
1128 let unsupported = CamelError::UnsupportedMediaType {
1129 consumed: "text/plain".into(),
1130 declared: "application/json".into(),
1131 };
1132 let not_acceptable = CamelError::NotAcceptable {
1133 accept: "application/xml".into(),
1134 produced: "application/json".into(),
1135 };
1136 assert_eq!(unsupported.classify(), "unsupported_media_type");
1137 assert_eq!(not_acceptable.classify(), "not_acceptable");
1138 }
1139
1140 #[test]
1141 fn variant_names_negotiation_errors() {
1142 let unsupported = CamelError::UnsupportedMediaType {
1143 consumed: "text/plain".into(),
1144 declared: "application/json".into(),
1145 };
1146 let not_acceptable = CamelError::NotAcceptable {
1147 accept: "application/xml".into(),
1148 produced: "application/json".into(),
1149 };
1150 assert_eq!(unsupported.variant_name(), "UnsupportedMediaType");
1151 assert_eq!(not_acceptable.variant_name(), "NotAcceptable");
1152 }
1153
1154 #[test]
1155 fn error_classification_label_is_pinned() {
1156 let type_conversion = CamelError::TypeConversionFailed(String::new());
1159 let validation = CamelError::ValidationError(String::new());
1160 let unsupported = CamelError::UnsupportedMediaType {
1161 consumed: String::new(),
1162 declared: String::new(),
1163 };
1164 let not_acceptable = CamelError::NotAcceptable {
1165 accept: String::new(),
1166 produced: String::new(),
1167 };
1168 let unauthenticated = CamelError::Unauthenticated(String::new());
1169 let unauthorized = CamelError::Unauthorized(String::new());
1170 let processor_with_source = CamelError::ProcessorErrorWithSource(
1171 String::new(),
1172 Arc::new(std::io::Error::other("inner")),
1173 );
1174 let consumer_stopping = CamelError::ConsumerStopping;
1175
1176 assert_eq!(
1177 type_conversion.classify(),
1178 "type_conversion",
1179 "TypeConversionFailed must classify as type_conversion (ADR-0096)"
1180 );
1181 assert_eq!(
1182 validation.classify(),
1183 "validation",
1184 "ValidationError must classify as validation"
1185 );
1186 assert_eq!(
1187 unsupported.classify(),
1188 "unsupported_media_type",
1189 "UnsupportedMediaType must classify as unsupported_media_type"
1190 );
1191 assert_eq!(
1192 not_acceptable.classify(),
1193 "not_acceptable",
1194 "NotAcceptable must classify as not_acceptable"
1195 );
1196 assert_eq!(
1197 unauthenticated.classify(),
1198 "unauthenticated",
1199 "Unauthenticated must classify as unauthenticated"
1200 );
1201 assert_eq!(
1202 unauthorized.classify(),
1203 "unauthorized",
1204 "Unauthorized must classify as unauthorized"
1205 );
1206 assert_eq!(
1207 processor_with_source.classify(),
1208 "processor",
1209 "ProcessorErrorWithSource must classify as processor"
1210 );
1211 assert_eq!(
1212 consumer_stopping.classify(),
1213 "consumer_stop",
1214 "ConsumerStopping must classify as consumer_stop"
1215 );
1216 }
1217
1218 #[test]
1219 fn display_negotiation_errors() {
1220 let unsupported = CamelError::UnsupportedMediaType {
1221 consumed: "text/plain".into(),
1222 declared: "application/json".into(),
1223 };
1224 let not_acceptable = CamelError::NotAcceptable {
1225 accept: "application/xml".into(),
1226 produced: "application/json".into(),
1227 };
1228 let unsupported_msg = unsupported.to_string();
1229 assert!(unsupported_msg.contains("text/plain"));
1230 assert!(unsupported_msg.contains("application/json"));
1231 let not_acceptable_msg = not_acceptable.to_string();
1232 assert!(not_acceptable_msg.contains("application/xml"));
1233 assert!(not_acceptable_msg.contains("application/json"));
1234 }
1235
1236 #[test]
1237 fn expression_failed_display_has_no_exchange_data() {
1238 let err = CamelError::ExpressionFailed {
1239 language: "rhai".to_string(),
1240 route_id: "r1".to_string(),
1241 step_id: "set_property#0".to_string(),
1242 verb: "set_property".to_string(),
1243 class: ExpressionErrorClass::Arithmetic,
1244 position: Some(ErrorPosition { line: 3, column: 8 }),
1245 conversion: None,
1246 cause: None,
1247 };
1248 let msg = err.to_string();
1249 assert!(msg.contains("arithmetic"), "missing class: {msg}");
1250 assert!(msg.contains("rhai"), "missing language: {msg}");
1251 assert!(msg.contains("set_property"), "missing verb/step: {msg}");
1252 assert!(msg.contains("3:8"), "missing position: {msg}");
1253 assert_eq!(
1255 msg,
1256 "expression failed: arithmetic in rhai `set_property` step \
1257 `set_property#0` (route `r1`) at 3:8"
1258 );
1259 }
1260
1261 #[test]
1262 fn expression_failed_variant_name() {
1263 let err = CamelError::ExpressionFailed {
1264 language: "rhai".to_string(),
1265 route_id: "r1".to_string(),
1266 step_id: "set_property#0".to_string(),
1267 verb: "set_property".to_string(),
1268 class: ExpressionErrorClass::Runtime,
1269 position: None,
1270 conversion: None,
1271 cause: None,
1272 };
1273 assert_eq!(err.variant_name(), "ExpressionFailed");
1274 }
1275
1276 #[test]
1277 fn config_validation_error_on_exception_conflict_display() {
1278 let err = ConfigValidationError::OnExceptionStepsHandledByConflict;
1279 let msg = format!("{err}");
1280 assert!(msg.contains("steps"));
1281 assert!(msg.contains("handled_by"));
1282 assert!(msg.contains("exclusive"));
1283 }
1284
1285 #[test]
1286 fn opaque_error_source_exposes_only_pointee() {
1287 let src = OpaqueErrorSource::new(Arc::new(SampleSource));
1288 let pointee = src.source().unwrap();
1289 assert!(pointee.downcast_ref::<SampleSource>().is_some());
1290 }
1291
1292 #[test]
1293 fn endpoint_creation_failed_with_source_aliases_to_plain() {
1294 let e = CamelError::EndpointCreationFailedWithSource(
1295 "d".to_string(),
1296 OpaqueErrorSource::new(Arc::new(SampleSource)),
1297 );
1298 assert_eq!(e.variant_name(), "EndpointCreationFailed");
1299 assert_eq!(e.classify(), "endpoint");
1300 assert_eq!(e.to_string(), "Endpoint creation failed: d");
1301 }
1302
1303 #[test]
1304 fn clone_preserves_variant_identity_for_all_error_samples() {
1305 for e in all_error_samples() {
1306 let c = e.clone();
1307 assert_eq!(c.variant_name(), e.variant_name());
1308 assert_eq!(c.classify(), e.classify());
1309 assert_eq!(c.to_string(), e.to_string());
1310 }
1311 }
1312
1313 #[test]
1314 fn camel_error_clone_preserves_source_provenance() {
1315 let e = CamelError::EndpointCreationFailedWithSource(
1316 "d".to_string(),
1317 OpaqueErrorSource::new(Arc::new(SampleSource)),
1318 );
1319 let c = e.clone();
1320 let wrapper = c.source().unwrap();
1324 let pointee = wrapper.source().unwrap();
1325 assert!(pointee.downcast_ref::<SampleSource>().is_some());
1326 }
1327}
1328
1329#[cfg(test)]
1330mod variant_name_tests {
1331 use super::{
1332 CamelError, ConfigValidationError, EndpointUriError, ExpressionErrorClass,
1333 OpaqueErrorSource, RedactedJson,
1334 };
1335 use std::sync::Arc;
1336
1337 #[test]
1348 fn variant_name_covers_all_variants() {
1349 let cases: Vec<(CamelError, &str)> = vec![
1350 (
1351 CamelError::ComponentNotFound("x".into()),
1352 "ComponentNotFound",
1353 ),
1354 (
1355 CamelError::EndpointCreationFailed("x".into()),
1356 "EndpointCreationFailed",
1357 ),
1358 (
1359 CamelError::EndpointCreationFailedWithSource(
1360 "x".into(),
1361 OpaqueErrorSource::new(Arc::new(std::io::Error::other("y"))),
1362 ),
1363 "EndpointCreationFailed", ),
1365 (CamelError::ProcessorError("x".into()), "ProcessorError"),
1366 (
1367 CamelError::ProcessorErrorWithSource(
1368 "x".into(),
1369 Arc::new(std::io::Error::other("y")),
1370 ),
1371 "ProcessorError", ),
1373 (
1374 CamelError::TypeConversionFailed("x".into()),
1375 "TypeConversionFailed",
1376 ),
1377 (CamelError::InvalidUri("x".into()), "InvalidUri"),
1378 (CamelError::ChannelClosed, "ChannelClosed"),
1379 (CamelError::RouteError("x".into()), "RouteError"),
1380 (CamelError::Io("x".into()), "Io"),
1381 (
1382 CamelError::DeadLetterChannelFailed("x".into()),
1383 "DeadLetterChannelFailed",
1384 ),
1385 (CamelError::CircuitOpen("x".into()), "CircuitOpen"),
1386 (
1387 CamelError::HttpOperationFailed {
1388 method: "GET".into(),
1389 url: "https://example.com".into(),
1390 status_code: 500,
1391 status_text: "Internal Server Error".into(),
1392 response_body: None,
1393 },
1394 "HttpOperationFailed",
1395 ),
1396 (CamelError::ConsumerStopping, "ConsumerStopping"),
1397 (CamelError::Config("x".into()), "Config"),
1398 (
1399 CamelError::ConfigValidation(ConfigValidationError::ThrottlerMaxRequestsZero),
1400 "ConfigValidation",
1401 ),
1402 (CamelError::AlreadyConsumed, "AlreadyConsumed"),
1403 (CamelError::StreamLimitExceeded(42), "StreamLimitExceeded"),
1404 (CamelError::Unauthenticated("x".into()), "Unauthenticated"),
1405 (CamelError::Unauthorized("x".into()), "Unauthorized"),
1406 (CamelError::ValidationError("bad".into()), "ValidationError"),
1407 (CamelError::TemplateReload("x".into()), "TemplateReload"),
1408 (
1409 CamelError::EndpointUri(EndpointUriError::MissingScheme),
1410 "EndpointUri",
1411 ),
1412 (
1413 CamelError::UnsupportedMediaType {
1414 consumed: "text/plain".into(),
1415 declared: "application/json".into(),
1416 },
1417 "UnsupportedMediaType",
1418 ),
1419 (
1420 CamelError::NotAcceptable {
1421 accept: "application/xml".into(),
1422 produced: "application/json".into(),
1423 },
1424 "NotAcceptable",
1425 ),
1426 (
1427 CamelError::ExpressionFailed {
1428 language: "rhai".into(),
1429 route_id: "r1".into(),
1430 step_id: "set_property#0".into(),
1431 verb: "set_property".into(),
1432 class: ExpressionErrorClass::Runtime,
1433 position: None,
1434 conversion: None,
1435 cause: None,
1436 },
1437 "ExpressionFailed",
1438 ),
1439 (
1440 CamelError::AuthProviderUnavailable("x".into()),
1441 "ProcessorError",
1442 ),
1443 (
1444 CamelError::Business {
1445 code: "ORDER_NOT_FOUND".into(),
1446 kind: "not-found".into(),
1447 message: "m".into(),
1448 data: None,
1449 },
1450 "Business",
1451 ),
1452 (
1453 CamelError::Transaction(crate::transaction::TransactionError::ManagerMissing {
1454 datasource: "pg".into(),
1455 }),
1456 "Transaction",
1457 ),
1458 ];
1459
1460 assert_eq!(
1461 cases.len(),
1462 29,
1463 "variant_name_covers_all_variants must cover every CamelError variant; \
1464 extend this table and the camel-dsl classification guard"
1465 );
1466
1467 for (err, expected) in cases {
1468 assert_eq!(
1469 err.variant_name(),
1470 expected,
1471 "variant_name mismatch for {:?}",
1472 err
1473 );
1474 }
1475 }
1476
1477 #[test]
1478 fn classify_and_variant_name_business() {
1479 let err = CamelError::Business {
1480 code: "ORDER_NOT_FOUND".to_string(),
1481 kind: "not-found".to_string(),
1482 message: "m".to_string(),
1483 data: None,
1484 };
1485
1486 assert_eq!(err.classify(), "business");
1487 assert_eq!(err.variant_name(), "Business");
1488 }
1489
1490 #[test]
1491 fn debug_on_data_newtype_redacts() {
1492 let data = RedactedJson::new(serde_json::json!({"secret": "hunter2"}));
1493 let err = CamelError::Business {
1494 code: "ORDER_NOT_FOUND".to_string(),
1495 kind: "not-found".to_string(),
1496 message: "m".to_string(),
1497 data: Some(data.clone()),
1498 };
1499
1500 let rendered = format!("{err:?}");
1501 assert!(
1502 rendered.contains("[redacted]"),
1503 "missing redaction marker: {rendered}"
1504 );
1505 assert!(!rendered.contains("hunter2"), "data leaked: {rendered}");
1506 assert_eq!(format!("{data:?}"), "[redacted]");
1507 assert_eq!(
1509 data,
1510 RedactedJson::new(serde_json::json!({"secret": "hunter2"}))
1511 );
1512 }
1513
1514 #[test]
1515 fn display_includes_code_and_kind_but_redacts_message_and_data() {
1516 let err = CamelError::Business {
1517 code: "ORDER_NOT_FOUND".to_string(),
1518 kind: "not-found".to_string(),
1519 message: "secret-message".to_string(),
1520 data: Some(RedactedJson::new(serde_json::json!({"secret": "hunter2"}))),
1521 };
1522
1523 let rendered = format!("{err}");
1524 assert!(
1525 rendered.contains("ORDER_NOT_FOUND"),
1526 "Display must include the code: {rendered}"
1527 );
1528 assert!(
1529 rendered.contains("not-found"),
1530 "Display must include the kind: {rendered}"
1531 );
1532 assert!(
1533 !rendered.contains("secret-message"),
1534 "Display leaked the log-only message: {rendered}"
1535 );
1536 assert!(
1537 !rendered.contains("hunter2"),
1538 "Display leaked the data payload: {rendered}"
1539 );
1540 }
1541
1542 #[test]
1543 fn auth_provider_unavailable_classifies_as_processor() {
1544 let err = CamelError::AuthProviderUnavailable("jwks down".into());
1545 assert_eq!(err.classify(), "processor");
1546 }
1547
1548 #[test]
1549 fn auth_provider_unavailable_variant_name_aliases_processor_error() {
1550 let err = CamelError::AuthProviderUnavailable("jwks down".into());
1551 assert_eq!(err.variant_name(), "ProcessorError");
1552 }
1553}