Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 8 lambda method to process IOException from close() in try-with-resources

Tags:

lambda

java-8

what is the proper syntax for Java 8 lambdas to wrap this

catch (Exception e) {
        throw JiraUtils.convertException(e);
}

and not repeat it in all methods that need this JiraRestClient?

@Override
public GTask loadTaskByKey(String key, Mappings mappings) throws ConnectorException {
    try(JiraRestClient client = JiraConnectionFactory.createClient(config.getServerInfo())) {
        final JiraTaskLoader loader = new JiraTaskLoader(client, config.getPriorities());
        return loader.loadTask(key);
    } catch (Exception e) {
        throw JiraUtils.convertException(e);
    }
}

@Override
public List<GTask> loadData(Mappings mappings, ProgressMonitor monitorIGNORED) throws ConnectorException {
    try(JiraRestClient client = JiraConnectionFactory.createClient(config.getServerInfo())) {
        final JiraTaskLoader loader = new JiraTaskLoader(client, config.getPriorities());
        return loader.loadTasks(config);
    } catch (Exception e) {
        throw JiraUtils.convertException(e);
    }
}

note: removing the catch() block leads to compilation error:

unreported exception java.io.IOException; must be caught or declared to be thrown
  exception thrown from implicit call to close() on resource variable 'client'

here is the link to JiraRestClient:

like image 403
Alex Avatar asked Oct 24 '25 18:10

Alex


1 Answers

You can do it like this:

@Override
public GTask loadTaskByKey(String key, Mappings mappings) throws ConnectorException {
  return withJiraRestClient(client -> {
    final JiraTaskLoader loader = new JiraTaskLoader(client, config.getPriorities());
    return loader.loadTask(key);
  });
}

@Override
public List<GTask> loadData(Mappings mappings, ProgressMonitor monitorIGNORED) throws ConnectorException {
  return withJiraRestClient(client -> {
    final JiraTaskLoader loader = new JiraTaskLoader(client, config.getPriorities());
    return loader.loadTasks(config);
  });
}

private <T> T withJiraRestClient(JiraRestClientAction<T> f) throws ConnectorException {
  try (JiraRestClient client = JiraConnectionFactory.createClient(config.getServerInfo())) {
    return f.apply(client);
  } catch (IOException e) {
    throw JiraUtils.convertException(e);
  }
}

@FunctionalInterface
interface JiraRestClientAction<T> {
  T apply(JiraRestClient client) throws IOException;
}
like image 76
Vladimir Korenev Avatar answered Oct 26 '25 22:10

Vladimir Korenev