Skip to main content

camel_builder/
do_try.rs

1//! Builder types for the `doTry` / `doCatch` / `doFinally` EIP pattern.
2//!
3//! These builders provide a fluent API for constructing doTry scopes within
4//! a Camel route. Example:
5//!
6//! ```ignore
7//! RouteBuilder::from("direct:start")
8//!     .do_try()
9//!         .process(try_step)
10//!         .do_catch_exception(&["SomeError"])
11//!             .process(catch_step)
12//!         .end_do_catch()
13//!     .end_do_try()
14//! ```
15
16use crate::RouteBuilder;
17use camel_api::error_handler::ExceptionDisposition;
18use camel_api::{BoxProcessor, CamelError, FilterPredicate, OpaqueProcessor, PredicateSource};
19use camel_core::route::{BuilderStep, DoTryCatchClause, DoTryFinallyClause};
20use camel_processor::CatchMatcher;
21
22// ── doTry / doCatch / doFinally builders ────────────────────────────────────
23
24/// Builder for a `.do_try()` ... `.end_do_try()` block.
25pub struct DoTryBuilder {
26    parent: RouteBuilder,
27    try_steps: Vec<BuilderStep>,
28    catch_clauses: Vec<DoTryCatchClause>,
29    finally: Option<DoTryFinallyClause>,
30    finally_set: bool,
31}
32
33/// Builder for a `.do_catch_exception()` / `.do_catch_when()` / `.do_catch_all()` clause.
34pub struct DoCatchBuilder {
35    parent: DoTryBuilder,
36    matcher: CatchMatcher,
37    on_when: Option<PredicateSource>,
38    steps: Vec<BuilderStep>,
39    disposition: ExceptionDisposition,
40}
41
42/// Builder for a `.do_finally()` ... `.end_do_finally()` block.
43pub struct DoFinallyBuilder {
44    parent: DoTryBuilder,
45    steps: Vec<BuilderStep>,
46    on_when: Option<PredicateSource>,
47}
48
49impl RouteBuilder {
50    /// Open a `doTry` scope. Steps inside are protected by catch and finally clauses.
51    pub fn do_try(self) -> DoTryBuilder {
52        DoTryBuilder {
53            parent: self,
54            try_steps: Vec::new(),
55            catch_clauses: Vec::new(),
56            finally: None,
57            finally_set: false,
58        }
59    }
60}
61
62impl DoTryBuilder {
63    /// Add a step to the try block.
64    pub fn process(mut self, processor: BoxProcessor) -> Self {
65        self.try_steps
66            .push(BuilderStep::Processor(OpaqueProcessor(processor)));
67        self
68    }
69
70    /// Open a catch clause that matches errors by variant name(s).
71    ///
72    /// Use `"*"` to match any variant (catch-all).
73    pub fn do_catch_exception(self, variants: &[&str]) -> DoCatchBuilder {
74        DoCatchBuilder {
75            parent: self,
76            matcher: CatchMatcher::ByVariant(variants.iter().map(|s| (*s).to_string()).collect()),
77            on_when: None,
78            steps: Vec::new(),
79            disposition: ExceptionDisposition::Handled,
80        }
81    }
82
83    /// Open a catch clause that matches errors by a predicate over the exchange.
84    pub fn do_catch_when(self, predicate: FilterPredicate) -> DoCatchBuilder {
85        DoCatchBuilder {
86            parent: self,
87            matcher: CatchMatcher::Predicate(PredicateSource::Sync(predicate)),
88            on_when: None,
89            steps: Vec::new(),
90            disposition: ExceptionDisposition::Handled,
91        }
92    }
93
94    /// Open a catch-all clause (matches any error variant).
95    pub fn do_catch_all(self) -> DoCatchBuilder {
96        self.do_catch_exception(&["*"])
97    }
98
99    /// Open a `doFinally` block.
100    ///
101    /// # Errors
102    ///
103    /// Returns `Err(CamelError::RouteError(_))` if `do_finally` has already
104    /// been called on this scope.
105    pub fn do_finally(self) -> Result<DoFinallyBuilder, CamelError> {
106        if self.finally_set {
107            return Err(CamelError::RouteError(
108                "do_finally can only be called once per do_try scope".into(),
109            ));
110        }
111        Ok(DoFinallyBuilder {
112            parent: self,
113            steps: Vec::new(),
114            on_when: None,
115        })
116    }
117
118    /// Close the `doTry` scope and return the parent `RouteBuilder`.
119    pub fn end_do_try(self) -> RouteBuilder {
120        let mut parent = self.parent;
121        parent.steps.push(BuilderStep::DoTry {
122            try_steps: self.try_steps,
123            catches: self.catch_clauses,
124            finally: self.finally,
125        });
126        parent
127    }
128}
129
130impl DoCatchBuilder {
131    /// Add a step to the catch clause's sub-pipeline.
132    pub fn process(mut self, processor: BoxProcessor) -> Self {
133        self.steps
134            .push(BuilderStep::Processor(OpaqueProcessor(processor)));
135        self
136    }
137
138    /// Set an additional predicate that must also match for this catch clause to fire.
139    pub fn on_when(mut self, predicate: FilterPredicate) -> Self {
140        self.on_when = Some(PredicateSource::Sync(predicate));
141        self
142    }
143
144    /// Mark this catch clause as handled: the caught error is absorbed
145    /// and the clause's exchange becomes the final result (no re-throw).
146    ///
147    /// Only `Handled` and `Propagate` are supported. There is intentionally
148    /// no general `disposition(value)` setter, so `Continued` is
149    /// unrepresentable at the type level.
150    ///
151    /// Valid use (compiles):
152    ///
153    /// ```
154    /// # use camel_builder::RouteBuilder;
155    /// let _ = RouteBuilder::from("direct:start").route_id("x").do_try()
156    ///     .do_catch_exception(&["E"])
157    ///     .handled();
158    /// ```
159    ///
160    /// Rejected — does not compile (no `disposition` method exists):
161    ///
162    /// ```compile_fail
163    /// # use camel_builder::RouteBuilder;
164    /// # use camel_api::error_handler::ExceptionDisposition;
165    /// let b = RouteBuilder::from("direct:start").route_id("x").do_try()
166    ///     .do_catch_exception(&["E"]);
167    /// b.disposition(ExceptionDisposition::Continued);
168    /// ```
169    pub fn handled(mut self) -> Self {
170        self.disposition = ExceptionDisposition::Handled;
171        self
172    }
173
174    /// Mark this catch clause as propagating: the clause runs for
175    /// side-effects and the original error is re-thrown.
176    ///
177    /// Only `Handled` and `Propagate` are supported. There is intentionally
178    /// no general `disposition(value)` setter, so `Continued` is
179    /// unrepresentable at the type level (semantically ambiguous at
180    /// catch-clause scope; `.continued()` is deliberately not provided).
181    pub fn propagate(mut self) -> Self {
182        self.disposition = ExceptionDisposition::Propagate;
183        self
184    }
185
186    /// Close the catch clause and return the parent `DoTryBuilder`.
187    pub fn end_do_catch(self) -> DoTryBuilder {
188        let mut parent = self.parent;
189        parent.catch_clauses.push(DoTryCatchClause {
190            matcher: self.matcher,
191            on_when: self.on_when,
192            disposition: self.disposition,
193            steps: self.steps,
194        });
195        parent
196    }
197}
198
199impl DoFinallyBuilder {
200    /// Add a step to the finally block.
201    pub fn process(mut self, processor: BoxProcessor) -> Self {
202        self.steps
203            .push(BuilderStep::Processor(OpaqueProcessor(processor)));
204        self
205    }
206
207    /// Set an optional predicate that gates whether the finally block runs.
208    pub fn on_when(mut self, predicate: FilterPredicate) -> Self {
209        self.on_when = Some(PredicateSource::Sync(predicate));
210        self
211    }
212
213    /// Close the finally block and return the parent `DoTryBuilder`.
214    pub fn end_do_finally(self) -> DoTryBuilder {
215        let mut parent = self.parent;
216        parent.finally_set = true;
217        parent.finally = Some(DoTryFinallyClause {
218            on_when: self.on_when,
219            steps: self.steps,
220        });
221        parent
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use crate::RouteBuilder;
228    use camel_api::error_handler::ExceptionDisposition;
229    use camel_api::{BoxProcessor, BoxProcessorExt, CamelError};
230    use camel_core::route::BuilderStep;
231    use camel_processor::CatchMatcher;
232
233    fn passthrough() -> BoxProcessor {
234        BoxProcessor::from_fn(move |ex| Box::pin(async move { Ok(ex) }))
235    }
236
237    #[test]
238    fn do_try_builder_assembles_correct_shape() {
239        let route = RouteBuilder::from("direct:start")
240            .route_id("do-try-shape")
241            .do_try()
242            .process(passthrough())
243            .do_catch_exception(&["ProcessorError"])
244            .handled()
245            .process(passthrough())
246            .end_do_catch()
247            .do_finally()
248            .unwrap()
249            .process(passthrough())
250            .end_do_finally()
251            .end_do_try();
252
253        let config = route.build().unwrap();
254        assert_eq!(config.steps().len(), 1, "expected exactly one step");
255        let BuilderStep::DoTry {
256            try_steps,
257            catches,
258            finally,
259        } = &config.steps()[0]
260        else {
261            panic!("the single step must be a DoTry variant");
262        };
263        assert_eq!(try_steps.len(), 1, "try block must have one step");
264        assert_eq!(catches.len(), 1, "expected exactly one catch clause");
265        assert_eq!(catches[0].disposition, ExceptionDisposition::Handled);
266        assert!(
267            matches!(&catches[0].matcher, CatchMatcher::ByVariant(v) if v == &["ProcessorError".to_string()]),
268            "catch matcher must be ByVariant([\"ProcessorError\"])"
269        );
270        assert_eq!(catches[0].steps.len(), 1, "catch clause must have one step");
271        let finally = finally.as_ref().expect("finally block must be present");
272        assert_eq!(finally.steps.len(), 1, "finally block must have one step");
273    }
274
275    #[test]
276    fn do_try_builder_try_steps_are_builder_steps() {
277        let route = RouteBuilder::from("direct:start")
278            .route_id("do-try-builder-steps")
279            .do_try()
280            .process(passthrough())
281            .end_do_try();
282
283        let config = route.build().unwrap();
284        let BuilderStep::DoTry { try_steps, .. } = &config.steps()[0] else {
285            panic!("the single step must be a DoTry variant");
286        };
287        assert!(
288            matches!(try_steps.first(), Some(BuilderStep::Processor(_))),
289            ".process() must store the step as BuilderStep::Processor"
290        );
291    }
292
293    #[test]
294    fn do_try_builder_disposition_sugar_methods() {
295        // handled route
296        let catch = RouteBuilder::from("direct:a")
297            .route_id("do-try-sugar-a")
298            .do_try()
299            .process(passthrough())
300            .do_catch_exception(&["Io"])
301            .handled();
302        assert_eq!(catch.disposition, ExceptionDisposition::Handled);
303        let _ = catch.end_do_catch().end_do_try().build().unwrap();
304
305        // propagate route
306        let catch = RouteBuilder::from("direct:b")
307            .route_id("do-try-sugar-b")
308            .do_try()
309            .process(passthrough())
310            .do_catch_exception(&["Io"])
311            .propagate();
312        assert_eq!(catch.disposition, ExceptionDisposition::Propagate);
313        let _ = catch.end_do_catch().end_do_try().build().unwrap();
314    }
315
316    #[test]
317    fn do_finally_called_twice_returns_err() {
318        let result = RouteBuilder::from("direct:start")
319            .route_id("do-try-double-finally")
320            .do_try()
321            .process(passthrough())
322            .do_finally()
323            .unwrap()
324            .process(passthrough())
325            .end_do_finally()
326            .do_finally();
327        match result {
328            Err(CamelError::RouteError(msg)) => {
329                assert!(
330                    msg.contains("do_finally can only be called once"),
331                    "unexpected message: {msg}"
332                );
333            }
334            _ => panic!("expected Err(RouteError)"),
335        }
336    }
337}