5.6. Action exceptions

Actions often invoke services that encapsulate complex business logic. These services may throw business exceptions that the action code should handle.

Handling a business exception with a POJO action

The following example invokes an action that catches a business exception, adds a error message to the context, and returns a result event identifier. The result is treated as a flow event which the calling flow can then respond to.

<evaluate expression="bookingAction.makeBooking(booking, flowRequestContext)" />	
        	
public class BookingAction {
   public String makeBooking(Booking booking, RequestContext context) {
       try {
           BookingConfirmation confirmation = bookingService.make(booking);
           context.getFlowScope().put("confirmation", confirmation);
           return "success";
       } catch (RoomNotAvailableException e) {
           context.addMessage(new MessageBuilder().error().
               .defaultText("No room is available at this hotel").build());
           return "error";
       }
   }
}
			

Handling a business exception with a MultiAction

The following example is functionally equivlant to the last, but implemented as a MultiAction instead of a POJO action. The MultiAction requires its action methods to be of the signature Event ${methodName}(RequestContext), providing stronger type safety, while a POJO action allows for more freedom.

<evaluate expression="bookingAction.makeBooking" />	
        	
public class BookingAction extends MultiAction {
   public Event makeBooking(RequestContext context) {
       try {
           Booking booking = (Booking) context.getFlowScope().get("booking");
           BookingConfirmation confirmation = bookingService.make(booking);
           context.getFlowScope().put("confirmation", confirmation);
           return success();
       } catch (RoomNotAvailableException e) {
           context.getMessageContext().addMessage(new MessageBuilder().error().
               .defaultText("No room is available at this hotel").build());
           return error();
       }
   }
}