How can I fail all but a few commands with an explicit exception?


(Elijah Rippeth) #1

I often want to model things that require a verification or disallows certain changes until a criteria is met.

For these types of scenarios, I tend to bifurcate my Behavior. Consider a user entity who is awaiting email confirmation in the following pseudocode…

class UserEntity extends PersistentEntity {

  import UserEntity._

  override type Command = InternalUserCommand[_]
  override type Event = InternalUserEvent
  override type State = Option[UserState]

  override def initialState: State = None

  override def behavior: Behavior = {
    case None => awaitingResponse()
    case Some(state) => verifiedUser(state)
  }

  def awaitingResponse() = Actions()
    /* email sent; awaiting a verification command. All else are bad... */

  def verifiedUser(state: UserState) = Actions()
    /* ... */

}

From this question, I know there will be a default command handler response if I omit the onCommand – is there a way to provide a custom exception?


(Alan Klikic) #2

@erip if you need to return a custom exception for invalid command you could use ctx.commandFailed and provide a custom exception there.
It will not be a default one but you need to specify it explicitly.
Is this what you need or?


(Elijah Rippeth) #3

Sorry, I wasn’t very clear. If I have a large number of commands, it becomes cumbersome to enumerate them all with a ctx.commandFailed in the following way:

def awaitingResponse() = Actions()
    /* email sent; awaiting a verification command. All else are bad... */
   .onCommand[A, B] {
      case (_: A, ctx, _) => ctx.commandFailed(...)
    }
   .onCommand[C, D] {
      case (_: C, ctx, _) => ctx.commandFailed(...)
    }

(Alan Klikic) #4

@erip so you need a custom PersistentEntity.UnhandledCommandException per behavior so you can distringuish in what state entity is on ask side if command is not implemented.
I did not find anything like this available.