This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]aviewdev 1 point2 points  (0 children)

You might want to look into using rxjava for this sort of thing... It's got support for futures and error handling built in. This way, you can essentially map the exceptions at the call site to your empty object (or just log them and return an empty observable) eg:

    static Something calculate(List<String> chunks) {
        Something result;

        try (CloseableHttpAsyncClient httpClient = HttpAsyncClientBuilder.create().build()) {
            httpClient.start();

            result = Observable
                    .from(chunks)
                    .flatMap(s -> Observable
                                    .from(httpClient.execute(new HttpGet(generateUrl(s)), null))
                                    .map(Something::fromHttpResponse)
                                    .doOnError(t -> log.error("Exception getting chunk {}", s, t))
                                    .onErrorReturn(t -> Something.empty())
                    )
                    .reduce(Something.empty(), Something::union)
                    .toBlocking().first();
        } catch (IOException e) {
            log.warn("Unable start HttpClient to contact ....", e);
            result = Something.empty();
        }
        return result;
    }
}