首页 > 解决方案 > 在 java 8 可选过滤器中抛出异常是一种不好的做法

问题描述

我想利用 java 8 optional 来验证接收到的对象的值(作为响应)。我很想知道,如果按照以下方式进行操作是不好的做法。

Optional.ofNullable(response)
.map(Response::getStatus)
.filter(status -> {
    if (status == Status.REJECTED)
        throw new RequestRejectedException("some exception");
    else if (status == Status.LOCKED)
        throw new ResourceLockedException("some other exception");
    return true;
})
.orElse(Status.UNAVAILABLE);

想知道,如果这样写上面的东西是否可以接受,或者是否有更好的方法,请提出建议。

标签: javaexceptionjava-8filteringoptional

解决方案


不,这不好。

return true;

你不过滤任何东西,是吗?知道状态后处理异常会更好。

final String status = Optional.ofNullable(response)
                              .map(Response::getStatus)
                              .orElse(Status.UNAVAILABLE);

if ("rejected".equals(status)) {
    throw new RequestRejectedException("some exception");
}

从您的评论来看,您似乎明白这Optional是为了什么。无需警告您这是不恰当的用法。


推荐阅读