繁体   English   中英

流-过滤所有未抛出异常

[英]Streams - Filter all not throwing exception

假设我有一个报告流,并且有一个检查用户是否有权阅读每个报告的方法。 如果用户没有权限,此方法将引发异常

checkReadAuthorization(Report report) throw AccessViolationException;

有没有一种方法可以过滤掉此方法引发异常的所有报表? 就像是:

reports.stream()
.filterThrowingException(this::checkReadAuthorization);

现在,我有一个函数,如果引发异常,则返回true或false,但是我想知道是否有更好的方法可以实现此目的

private boolean checkAuthorization(Report report) {
    try {
        checkReadAuthorization(report);
        return true;
    } catch(AccessViolationException ex) {
        return false;
    }
}

然后在这样的过滤器中使用它

return dossiers.stream()
    .filter(this::checkAuthorization)
    .collect(Collectors.toList());

当前的Stream-API中没有类似于“ filterThrowingException ”的内容。 您只能使用Stream::filter内的try-catch来决定保留还是过滤掉Report

List<Report> filtered = list.stream().filter(report -> {
    try {
        this.checkAuthorization(report);
    } catch (AccessViolationException ex) {
        return false;
    }
    return true;
}).collect(Collectors.toList());

就个人而言,我建议更改方法checkReadAuthorization的接口以返回指示输入是否有效的boolean

private boolean checkReadAuthorization(Report report) { /* ... */ }

此结果可用作过滤器中的谓词。

List<Report> filtered = list.stream()
                            .filter(this::checkReadAuthorization)
                            .collect(Collectors.toList());

简介:更好地更改验证类和方法的设计,而不是尝试Stream-API来适应不是最佳的方法。

我将交换checkReadAuthorizationcheckAuthorization

private boolean checkAuthorization(Report report) 
{
    // put here the logic that checks for authorization, but without throwing exception
}

void checkReadAuthorization(Report report) throw AccessViolationException
{
    if (!checkAuthorization(report)) {
        throw new AccessViolationException ();
    }
}

这样,您就不会使用异常作为条件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM