Search code examples
masstransit

Permission checking/exception handling in Mass Transit State Machine


I am trying to implement permission checking in my saga state machine. As I need to use an external resource for this I outsourced the permission checking(as well as some other code that relies on the external resource) to an activity. I am trying to achieve the following: If the permission check fails, i throw an exception inside my activity. If the exception was thrown, the state machine returns an error response, and nothing else happens. If there was no exception thrown, transition to the next state, and return a success response. My state machine code currently looks something like this:

During(State1,
When(Event1)
.Activity(x => x.ofType<PermissionCheckActivity>())
.Catch<Exception>(x => x.RespondAsync(async context => new ErrorResponse())
.RespondAsync(async context => new SuccessResponse())
.TransitionTo(State2)

Now, I know that this is wrong, and why this is wrong: The RespondAsync and TransitionTo lines run regardless of the Catch catching any exceptions. However I coudn't find a way to check if there was an exception in the Activity. Is there a way to check for that? Or is my approach wrong? Is it okay to check for permission in an activity like this? Is this the way to handle exceptions generally, or should I handle them inside the activity? I am quite new to Mass Transit, so apologies, if the questions are stupid.


Solution

  • Change you state machine:

    During(State1,
    When(Event1)
    .Activity(x => x.ofType<PermissionCheckActivity>())
    .RespondAsync(async context => new SuccessResponse())
    .TransitionTo(State2)
    .Catch<Exception>(x => x.RespondAsync(async context => new ErrorResponse())