Detecting when an asynchronous JMS MessageConsumer has an Exception?

1.3k views Asked by At

I'm processing messages using a JMS MessageConsumer with a MessageListener. If something happens that causes the MessageConsumer to stop receiving and processing messages -- for example, if the underlying connection closes -- how can I detect it? There doesn't seem to be any notification mechanism that I can find in the spec.

I think the question is clear as is, but if you'd like me to post code to clarify the question, just ask!

In case it's important, I'm using ActiveMQ 5.8, although obviously I'd like a scheme that's not implementation-specific.

1

There are 1 answers

6
raffian On BEST ANSWER

Use ExceptionListener

If the JMS system detects a problem, it calls the listener's onException method:

public class MyConsumer implements ExceptionListener, MessageListener {

    private void init(){
        Connection connection = ... //create connection
        connection.setExceptionListener(this);
        connection.start();
    }

    public void onException(JMSException e){
        String errorCode = e.getErrorCode();
        Exception ex = e.getLinkedException();
        //clean up resources, or, attempt to reconnect 
    }

    public void onMessage(Message m){
       ...
}

Not much to it, really, the above is standard practice for standalone consumers; it's not implementation-specific; actually, quite the contrary as it's part of the spec!, so all JMS-compliant providers will support it.