Reputation: 15002
I got Unhandled exception works differently on two different methods
on the 2nd method getByIds
Which is making no sense.
I call the first method in the second method and put the try catch already.
Any idea for this exception? Thanks
@Override
public PostPayload getById(@NotNull UUID issueId) throws APIException {
try (...) {
return test.apply(responseIssue, issueAuxiliaryData);
} catch (IOException e) {
logger.error("Event='Unable to retrieve XXX ', issueId={}", issueId, e);
throw new APIException("Unable to retrieve XXX for issueId=" + issueId, e);
}
}
@Override
public List<PostPayload> getByIds(@NotNull Set<UUID> issueIds) throws APIException {
return issueIds.parallelStream()
.map(issueId -> {
try {
return this.getById(issueId, channelId, false);
} catch (IOException | APIException e) {
logger.error("Event='Unable to retrieve XXX ', issueId={}", issueId, e);
throw new APIException("Unable to retrieve XXX for issueId=" + issueId, e);
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
Upvotes: 1
Views: 72
Reputation: 15683
You can do two things with an exception:
throw
itYour first method has a throws APIException
in its signature, so throwing APIException
is a valid thing to do.
But how is this different from your other method ? There you are trying to throw the exception from within a lambda passed to a stream().map()
method. From the documentations we can find out the functional interface corresponding to this lambda:
public interface Function<T, R> {
R apply(T t);
}
From the signature we can see that it does not throw any checked exceptions, so it's a compilation error to throw APIException
from within the lambda (assuming APIException
is a checked exception)
A possible workaround is to define another version of your exception, that derives from RuntimeException
, for instance UncheckedApiException
. Then you can wrap the whole stream operation in one big try-catch block adn in the catch block you can throw the checked version:
@Override
public List<PostPayload> getByIds(@NotNull Set<UUID> issueIds) throws APIException {
try {
return issueIds.parallelStream()
.map(issueId -> {
try {
return this.getById(issueId, channelId, false);
} catch (IOException | APIException e) {
logger.error("Event='Unable to retrieve XXX ', issueId={}", issueId, e);
throw new UncheckedApiException("Unable to retrieve XXX for issueId=" + issueId, e);
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
} catch (UncheckedApiException e) {
throw new APIException(e);
}
}
Upvotes: 3