java.util.concurrent.CompletionStage - 如何处理异常?

标签 java java-8 java.util.concurrent

我试图在以下代码中找到更好的方法来处理多个异常:

public CompletionStage<Result> getRepositoryInfo(String repositoryOwner, String repositoryName) {
return repositoryInfoService.getRepositoryInfo(repositoryOwner, repositoryName)
        .handle((repositoryInfo, ex) -> {
            if (repositoryInfo != null) {
                return ok(Json.toJson(repositoryInfo));
            } else {
                if (ex.getCause() instanceof GithubRepoNotFoundException) {
                    return notFound(Json.toJson("repo not found"));
                } else {
                    return internalServerError(Json.toJson("internal error"));
                }
            }
        });
}

此程序获取 github 存储库名称和所有者,并返回一些基本信息(如全名、描述、克隆的 url 等)。 repositoryInfoService.getRepositoryInfo() 返回对象或抛出 GithubRepoNotFoundExceptionGithubApiException。这个 instanceof 看起来真的很难看,我对此并不满意。另一种选择是重新抛出 ex.getCause(),但它也很糟糕。

最佳答案

有些库为 if 语句和特别是 instanceof 提供了更流畅的 API。

使用 javaslang matcher和 java 的 Optional 你的处理程序看起来像

.handle((repositoryInfo, ex) -> ofNullable(repositoryInfo)
    .map(info -> ok(toJson(info)))
    .orElse(Match(ex.getCause()).of(
        Case(of(GithubRepoNotFoundException.class), notFound(toJson("repo not found")),
        Case(any(), internalServerError(toJson("internal error")))));

关于java.util.concurrent.CompletionStage - 如何处理异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37653270/

相关文章:

java - 如何在 Windows 上使用命令行执行具有外部依赖项的 jar 文件?

java - 如何在 Stream 链中调用 setter

java - 如何修复 SSLProtocolException : handshake alert: unrecognized_name without disabling SNI

java - PipedInputStream、PipedOutputStream 和进程

java - 我通过intellij idea运行Kettle 8.3源,无法实例化类org.pentaho.di.engine.ui.RunConfigurationLifecycleListener

java - Vim 编辑器很聪明吗?

java - 在 Docker 中解密 Spring 属性值

java - Java 8 Stream 是安全的返回类型吗?

java - 多线程应用程序中的Java垃圾回收以获取局部变量

java - AtomicInteger 与 Java 中的同步 int 变量 : performance difference