Ali*_*ali 2 java spring reactive spring-webflux spring-webclient
在 Spring WebFlux 链中,我使用了有时可能返回 null 的映射操作,并且我收到警告:
Return null or something nullable from lambda in transformation mehtod。
我相信当数据为空时,它实际上不会将输入映射到,null但会引发异常。
处理这种情况的最佳方法是什么?
可为空的 Map 方法:
public Pojo parseJson(String json) {
try {
// parse
return pojo;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我的反应链:
public Mono<Pojo> query(long id) {
Integer value = idMapper.getValue(id);
if (value != null) {
return repo.query(value)
Parse Method
|
v
.map(this::parse);
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
在函数式/响应式世界中工作时,您应该尽量避免所有空检查,并尽量不要从任何方法中返回空值。
而是Optional<T>在存在返回空值的风险时返回,并在返回Mono.error的函数中出现错误时返回Mono。或者,Mono.empty如果您只想跳过返回某些内容,请返回。
通过使用 optional ,您可以将代码重写为更清晰的内容。
public Optional<Pojo> parseJson(String json) {
// Return an optional if there is risk for a null.
return Optional.ofNullable(new Pojo());
}
private final IdMapper idMapper = new IdMapper();
private final Repo repo = new Repo();
public Mono<Pojo> query(long id) {
// By returning an optional from the idMapper
// you can chain on and avoid null checks.
return idMapper.getValue(id).map(integer -> repo.query(integer)
.map(s -> parseJson(s).map(Mono::just)
.orElse(Mono.empty())))
.orElse(Mono.error(() -> new NotFoundException("No Pojo with ID could be found")));
}
class Pojo {
// Some pojo class
}
class Repo {
public Mono<String> query(long id) {
return Mono.just("Foo");
}
}
class IdMapper {
public Optional<Integer> getValue(long id) {
// Here return an Optional instead of null!
return Optional.of(1);
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我返回 Optionals 并根据发生的情况做出一些决定是返回 Mono.empty 还是 Mono.error 。
| 归档时间: |
|
| 查看次数: |
3274 次 |
| 最近记录: |