java - 在 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);
想知道,如果这样写上面的东西是否可以接受,或者是否有更好的方法,请提出建议。
解决方案
不,这不好。
return true;
你不过滤任何东西,是吗?知道状态后处理异常会更好。
final String status = Optional.ofNullable(response)
.map(Response::getStatus)
.orElse(Status.UNAVAILABLE);
if ("rejected".equals(status)) {
throw new RequestRejectedException("some exception");
}
从您的评论来看,您似乎明白这Optional
是为了什么。无需警告您这是不恰当的用法。
推荐阅读
- php - PHP - 在关联数组和索引数组中获取多维数组的计数
- c# - WPF + PostSharp'ed 视图模型在一分钟内冻结
- python - 基于键向字典添加多个值
- alexa - 无法在音频播放结束时添加 .listen() 指令
- redis - 是否应该将所有使用 redis 缓存的 pod 限制在与 rediscache 本身相同的节点上?
- android - 如何创建具有特定控制器轴值的 MotionEvent?
- java - 找不到接口 org.springframework.data.domain.Pageable 的主要或默认构造函数
- rust - 删除临时值如何在 rust 中起作用?
- reactjs - React Redux 使用什么样的设计模式?
- angular - Angular 6 http post 到 IIS 上的实体框架无法在正文中传递参数