What happens when an exception occurs in JMS listener

Viewed 6359

I am using Default Message Listener Container. I have set session transacted property true in configuration.

My onMessage() method is this:

public void onMessage(Message message) {
    try {
        // Some code here
    } catch (JmsException jmse) {
        log.error(jmse);
    } catch (Throwable t) {
        log.error(t);
    }
}

As you can see I am handling the exception in a catch block.

My requirement is that if it is a JMS Exception, it should be resent, i.e. message redelivered to the listener/consumer as it happens when there is transaction rollback. How can that happen?

Can we manually rollback the transaction here? I think that is a possible solution but I dont how to do that in code.

Another generic question:

Since I am handling all the possible exceptions through a catch block, I guess there will not be a scenario of message redelivery i.e. transaction rollback since I am handling all the possible exceptions through the catch block. Am I right?

2 Answers

You don't need a SessionAwareMessageListener; simply throw the exception instead of catching it and the container will rollback the delivery.

Specifically, it will rollback if the exception is a JmsException, RuntimeException (or subclasses) or an Error.

You should generally not catch Throwable anyway; it's not good practice.

EDIT

public void onMessage(Message message) {
    try {
        // Some code here
    } 
    catch (JmsException jmse) {
        log.error(jmse);
        // Do some stuff
        throw new RuntimeException(jmse); // JMSException is checked so can't throw
    }
    catch (RuntimeException e) {
        log.error(e);
        throw e;
    }
    catch (Exception e) {
        log.error(t);
        throw new RuntimeException(e);
    }
}

Have you tried SessionAwareMessageListener ? Please check here

Related