Which is the best way to handle exception in java MDB?

2.2k views Asked by At

I got this use case:

This diagram represents an enterprise model. Java EE technology on Weblogic 10.3 with the leverage of spring framework for IoC and AOP, JPA for persistence with spring jpatemplate, spring integration for the interaction frame. As you can see there is no coupling between the Service and the Gateway since spring integration add all the magic sugar needed.

Now I have to deal with the exception handling. All the chain has no checked exceptions: also the data access has no checked exception since jpatemplate wraps all the sql exception in runtime exceptions.

So the only checked exception that I handle is on the MDB

@Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void onMessage(Message message) {
        try {
            TextMessage textMessage = (TextMessage) message;
            String stringMessage = textMessage.getText();

            OnlineEventMessage<? extends Serializable> event = eventMessageParser.parse(stringMessage);

            legacyEventMessageService.handle(event);
        } catch (JMSException e) {
            logger.error("si e' verificato un errore JMS nel processamento dell'evento {}", message, e);
        }
    }

I noticed that if I get a NPE for example on some component of the chain the message is rolled back on the JMS queue and the process is looped back.

Which is the best way to handle exceptions in this scenario? Catch all the runtimeExceptions in the MDB?

Kind regards Massimo

1

There are 1 answers

2
Arjan Tijms On

Which is the best way to handle exceptions in this scenario? Catch all the runtimeExceptions in the MDB?

It depends on what you want to achieve. If feel from your description that you want to prevent the message being rolled back. Is that right?

In that case catching all run time exceptions gets you only so far. The system could also throw errors, which you won't catch then. So you have to catch Throwable instead. But, then the transaction could still time out, resulting in a roll-back.

In short, do you want your MDB to be transactional at all?

Also note that the transaction context from the sender does not propagate to the MDB.

Slightly off topic, but are you really sure you need jpatemplate? It seems pretty much everybody has agreed that the JPA API is fine by itself and doesn't need any 'enhancements' from Spring, including SpringSource themselves.