Invalid Business State Errors
Invalid Business State Errors
An invalid business state error is an error thrown during a state change operation where a business condition is not fulfilled. Invalid business state error types prevent a state change operation from happening. Often the client can solve the underlying business error and then retry the state change operation successfully.
For example, when purchasing an order, the following scenarios could generate invalid business state errors:
- An item in the cart isn't available in the requested quantity.
- The shopping cart is empty.
- A shipping address is missing.
Invalid business state error is mapped to the HTTP status code 409, which indicates the presence of a conflict. To help the client localize error messages and recover from this error type, the body of the HTTP response contains structured error messages.
Constructing Invalid Business State Errors
Unlike validation errors, which are generated during validation, invalid business state errors must be constructed manually.
In Commerce Engine, an invalid business state error is an Exception which implements the InvalidBusinessStateException interface. Each exception of type InvalidBusinessStateException can contain multiple StructuredErrorMessage objects, indicating why the failure state occurred.
For example, AvalabilityException is a fully constructed invalid business state error:
public class AvailabilityException extends EpSystemException implements InvalidBusinessStateException { private final List<StructuredErrorMessage> structuredErrorMessages; public AvailabilityException(final String message, final Collection<StructuredErrorMessage> structuredErrorMessages) { super(message); this.structuredErrorMessages = structuredErrorMessages == null ? emptyList() : ImmutableList.copyOf(structuredErrorMessages); } @Override public List<StructuredErrorMessage< getStructuredErrorMessages() { return structuredErrorMessages; } @Override public String getExceptionMessage() { return getMessage(); } }
Handling InvalidBusinessStateException Exceptions in Cortex
For automatic InvalidBusinessStateException handling when calling a Commerce Engine service, use one of the fromService methods in ReactiveAdapter.
The following is an example of calling a Commerce Engine service with automatic exception handling of an InvalidBusinessStateExeption.
Observable o = reactiveAdapter.fromService(() -> ceService.myMethod());
If an exception occurs StructuredErrorMessage objects in the exception are converted to Message or LinkedMessage objects. These message objects are wrapped in a ResourceOperationFailure, and returned on the Rx type's error channel. This process is transparent to the user.
In addition to being consumable by Cortex, converting StructuredErrorMessage objects to Message or LinkedMessage allows these objects to contain information about links.