在 java 8 个可选过滤器中抛出异常是一种不好的做法吗
Is it a bad practice to throw exceptions in java 8 optional filters
我想利用 java 8 可选来验证接收到的对象的值(作为响应)。我很想知道,按照下面的做法是否是一种不好的做法。
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);
想知道,如果可以这样写,或者有更好的方法,请指教。
不行,不行。
return true;
你没有过滤任何东西,是吗?最好知道状态后再处理异常
final String status = Optional.ofNullable(response)
.map(Response::getStatus)
.orElse(Status.UNAVAILABLE);
if ("rejected".equals(status)) {
throw new RequestRejectedException("some exception");
}
从你的评论来看,你似乎明白了Optional
是什么意思。无需警告您这是不当的用法。
我想利用 java 8 可选来验证接收到的对象的值(作为响应)。我很想知道,按照下面的做法是否是一种不好的做法。
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);
想知道,如果可以这样写,或者有更好的方法,请指教。
不行,不行。
return true;
你没有过滤任何东西,是吗?最好知道状态后再处理异常
final String status = Optional.ofNullable(response)
.map(Response::getStatus)
.orElse(Status.UNAVAILABLE);
if ("rejected".equals(status)) {
throw new RequestRejectedException("some exception");
}
从你的评论来看,你似乎明白了Optional
是什么意思。无需警告您这是不当的用法。