您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在将来可以将异常映射到其他异常类型?

在将来可以将异常映射到其他异常类型?

您可以使用CompletableFuture#handle(BiFunction)。例如

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;
});

如果ask完成并带有异常,translatedException则将完成并带有潜在转换的异常。否则,它将具有相同的成功结果值。

关于我在代码中的注释,该handle方法期望未声明BiFunctionapply方法方法抛出Throwable。因此,lambda主体本身无法抛出Throwable。参数e是类型,Throwable因此您不能throw直接使用它。你可以将它转换为RuntimeException,如果你知道它的那种类型的,或者你可以在一个包装它RuntimeExceptionthrow那个。

其他 2022/1/1 18:33:32 有563人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶