简体   繁体   中英

Recursive call in catch block method who return value

This is my problem :

I have to get a connection to a broker service (here activemq), so I do that :

public GenericMessageManager(String url, String producerQueue,
        String consumerQueue) {

    Connection connection;
    try {
        connection = getConnection(url);
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = createProducer(producerQueue);
        consumer = createConsumer(consumerQueue);
        connection.start();
        logger.info("Connection to broker started");
    } catch (JMSException e) {

    }
}

private Connection getConnection(String url) {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
            url);
    try {
        Connection connection = connectionFactory.createConnection();
        return connection;
    } catch (JMSException e) {
        if (e.getLinkedException() instanceof SocketTimeoutException) {
            logger.warn(url + " not responding, try on localhost");
            getConnection("tcp://127.0.0.1:61616");
        }
    }
    return null;
}

In the getConnection() method I do a recursive call with another url if I catch a SocketTimeOutException. That's work but the first call return null before the second and I get a NPE on connection.createSession(...);

I don't know what can I do to solve it ?

I wouldn't solve this via recursion, since it doesn't seem intuitively to be a problem requiring recursion as such. I would rather configure a list of valid hosts, and try them in order eg

for (String host : hosts) {
   try {
      Connection c = getConnection(host);
      if (c != null) { 
         return c;
      }
      // log here (not sure I'd return null at all, mind)
   }
   catch (Exception e) {
      // log here...
   }
}
// fail completely

and consistently throw an exception in the case of failure, rather than confuse the meaning/handling of exceptions and nulls.

The above isolates the making of the connection (and error handling) from the retry mechanism, and arguably makes it simpler and more comprehensible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM