Map exception in completable future to a different exception type?

柔情痞子 提交于 2019-12-01 11:38:44

You can use CompletableFuture#handle(BiFunction). For example

CompletableFuture<String> ask = CompletableFuture.supplyAsync(() -> {
    throw new IndexOutOfBoundsException();
});
CompletableFuture<String> translatedException = ask.handle((r, e) -> {
    if (e != null) {
        if (e instanceof IndexOutOfBoundsException) {
            throw new IllegalArgumentException();
        }
        throw (RuntimeException) e; // this is sketchy, handle it differently, maybe by wrapping it in a RuntimeException
    }
    return r;
});

If ask completed with an exception, then translatedException will complete with a potentially transformed exception. Otherwise, it will have the same success result value.

Concerning my comment in the code, the handle method expects a BiFunction whose apply method is not declared to throw a Throwable. As such, the lambda body cannot itself throw a Throwable. The parameter e is of type Throwable so you can't throw it directly. You can cast it to RuntimeException if you know it's of that type, or you can wrap it in a RuntimeException and throw that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!