javaspringspring-integrationenterprise-integration

MessageHandlingException message in error channel


I have written an Exception handler class that looks at the default Spring Integration errorChannel for incoming messages of type Message<TradeProcessingContext> message:

@Slf4j
public class ExceptionHandler {

    @Autowired
    private ExceptionDAO exceptionDAO;


    @ServiceActivator(inputChannel = DEFAULT_ERROR_CHANNEL)
    public void handleTradeError(Message<TradeProcessingContext> message) {

        TradeProcessingContext tradeProcessingContext = message.getPayload();

        if (tradeProcessingContext != null) {
          //store in database
        }
    }

}

I have handler implementations as follows:

@Slf4j
@MessageEndpoint
public class ChildHandler extends ParentHandler {

    @Autowired
    private SomeDAO someDAO;

    @ServiceActivator(inputChannel = INPUT_CHANNEL, outputChannel = DEFAULT_ERROR_CHANNEL)
    public Message<TradeProcessingContext> handle(final Event event) {
        return process(event);
    }

    @Override
    protected TradeDAO getDAO() {
        return someDAO;
    }
}

That invokes the parent process()

public abstract class ParentHandler implements Handler {

    @Resource
    private SomeService service;


    public Message<TradeProcessingContext> process(final Event event) {

        TradeProcessingContext tradeProcessingContext = new TradeProcessingContext();

        //set initial context

        try {
            List<Trade> trades = getDAO().findByEventId(event.getEventId());
            for (Trade trade : trades) {
                tradeProcessingContext.setRef(trade.getRef());
                Future<TradeProcessingContext> thread = service.doSomething(trade, tradeProcessingContext);
                tradeProcessingContext = thread.get();
            }
        } catch (Exception e) {
            return MessageBuilder.withPayload(tradeProcessingContext).build();
        }

        return null;
    }

I understand I can get org.springframework.messaging.MessageHandlingException: nested exception is java.lang.ClassCastException when the type is Message<MessageHandlingException> message in handleTradeError().

How can i improve this method so that such errors are taken care of also or the underlying tradeprocessingContext is also extracted from this type?


Solution

  • The error channel gets an ErrorMessage which has a Throwable payload. Usually the Throwable is a message handling exception with the original message in the failedMessage property and the exception in the cause.