Search code examples
masstransitsaga

Doesn't work exception catching in Masstransit saga's


I try to use saga with MassTransit 7.2.2. I have next event in my saga:

During(Submitted,
     When(OrderAccepted)
     .Then(x =>
     {
         logger.LogInformation($"Order {x.Instance.OrderId} accepted");
         throw new Exception("TEST");
     })
     .Catch<Exception>(x =>
     {
         x.If(
             context => context.Data.OrderId == 1002,
             activityBinder =>
                 activityBinder
                     .Then(y =>
                     {
                         logger.LogInformation($"Order {y.Instance.OrderId} catch exception and pass to Rejected");
                     })
                     .TransitionTo(Rejected)
         );

         return x;
     })
     .ThenAsync(c =>
     {
         return TakeProductCommand(c);
     })
     .TransitionTo(Accepted));

In code above I want to catch any exception that might be raised during handling of current event and put saga into Rejected state. But it doesn't work as I thought. I don't get into the Catch handler at all.

What I did wrong?


Solution

  • Your code is slightly malformed, and breaks the builder pattern chain.

    The changes are subtle, but significant.

    During(Submitted,
         When(OrderAccepted)
         .Then(x =>
         {
             logger.LogInformation($"Order {x.Instance.OrderId} accepted");
             throw new Exception("TEST");
         })
         .Catch<Exception>(x =>
             x.If(
                 context => context.Data.OrderId == 1002,
                 activityBinder =>
                     activityBinder
                         .Then(y =>
                         {
                             logger.LogInformation($"Order {y.Instance.OrderId} catch exception and pass to Rejected");
                         })
                         .TransitionTo(Rejected)
             )
         )
         .ThenAsync(c =>
         {
             return TakeProductCommand(c);
         })
         .TransitionTo(Accepted));