I have a rest controller that has an endpoint:
@GET
@Path("/reindex-record")
public String reindexRecord(@QueryParam("id") String id) {
if (StringUtils.isEmpty(id)) {
CompletableFuture.runAsync(
() -> runWithException(Reindexer::reindexAll));
} else {
CompletableFuture.runAsync(() -> runWithException(
() -> Reindexer.reindexOne(id)));
}
// return "ok" or throw WebApplciationException from runWithException method below
}
and here is my wrapper method - both methods - reindexAll and reindexOne throw checked exceptions so decided to use wrapper method and interface:
public interface RunnableWithException {
void run() throws Exception;
}
private void runWithException(RunnableWithException task) {
try {
task.run();
} catch (Exception e) {
log.error("Error occured during async task execution", e);
throw new WebApplicationException(
Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("Internal error occurred").build());
}
}
The problem is that I want to run this task asnychronously using CompleteableFuture and give a response only after given task is done or if there was an error throw WebApplicationException with INTERNAL_SERVER_ERROR status.
How would you implement that in my use-case with if/else?
EDIT: As of now I have this method:
@GET
@Path("/reindex-record")
public String reindexRecord(@QueryParam("id") String id) throws ExecutionException,
InterruptedException {
CompletableFuture<Void> task;
if (StringUtils.isEmpty(id)) {
task = CompletableFuture.runAsync(
() -> runWithException(Reindexer::reindexAll));
} else {
task = CompletableFuture.runAsync(() -> runWithException(
() -> Reindexer.reindexOne(id)));
}
return task.thenApply(x -> "ok")
.exceptionally(throwable -> {
log.error("Error occured during async task execution", throwable);
throw new WebApplicationException(Response.status(Response.Status.SERVICE_UNAVAILABLE)
.entity("Internal error occurred. Try again later")
.build());
}).get();
}
But if error is thrown by any of Reindexer methods I'm still getting status 500 with data:
{
"code": 500,
"message": "There was an error processing your request. It has been logged (ID 03f09a62b62b1649)."
}
Instead of 503 defined in my exceptionally
block.
Using dropwizard with JAX-RS if that matters.