Package akka.javasdk

Class CommandException

All Implemented Interfaces:
Serializable

public class CommandException extends IllegalArgumentException
An exception that can be thrown by user code to signal domain validation errors or business rule violations.

This exception is designed to be used in command handlers of KeyValueEntity, EventSourcedEntity, or Workflow components when the incoming command doesn't fulfill the requirements or the current state doesn't allow the command to be handled.

HTTP Response Behavior:

  • By default, CommandException is transformed into an HTTP 400 Bad Request response
  • The exception message becomes the response body
  • Can be caught and transformed into custom HTTP responses for fine-tuned error handling

Network Serialization: Only CommandException and its subtypes are serialized and sent over the network when components are called across different nodes. Other exceptions are transformed into generic HTTP 500 errors. The Jackson serialization is configured to ignore fields like stack trace or cause from the Throwable class.

Usage Examples:

Using error effects:


 // In a command handler
 if (value > 10000) {
   return effects().error("Increasing counter above 10000 is blocked");
 }
 

Throwing directly:


 // In a command handler
 if (value > 10000) {
   throw new CommandException("Increasing counter above 10000 is blocked");
 }
 

Creating custom subtypes:


 public class CounterLimitExceededException extends CommandException {
   public CounterLimitExceededException(String message) {
     super(message);
   }
 }

 // Usage
 throw new CounterLimitExceededException("Counter limit exceeded");
 

Error Handling in Endpoints:


 try {
   return componentClient
            .forEventSourcedEntity(counterId)
            .method(CounterEntity::increase)
            .invoke(value);
 } catch (CommandException e) {
   // Handle the command exception, e.g., return a bad request response
 }
 
See Also: