簡體   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