首页 > 解决方案 > 未处理的异常在两种不同的方法上的工作方式不同

问题描述

Unhandled exception works differently on two different methods采用了第二种方法,getByIds 这是没有意义的。我在第二种方法中调用第一种方法并已经把try catch。

这个例外有什么想法吗?谢谢

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

标签: javajava-8

解决方案


除了例外,您可以做两件事:

  1. 以某种方式处理它
  2. 重新throw_

你的第一个方法throws APIException在它的签名中有一个,所以抛出APIException是一个有效的事情。

但这与您的其他方法有何不同?在那里,您试图从传递给stream().map()方法的 lambda 中抛出异常。从文档中我们可以找到这个 lambda 对应的功能接口:

public interface Function<T, R> {
    R apply(T t);
}

从签名中我们可以看到它没有抛出任何已检查的异常,因此APIException从 lambda 中抛出是编译错误(假设APIException是已检查的异常)

一种可能的解决方法是定义另一个版本的异常,RuntimeException例如从UncheckedApiException. 然后你可以将整个流操作包装在一个大的 try-catch 块中,然后在 catch 块中你可以抛出检查的版本:

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

推荐阅读