我正在使用Spring Web Flux创建一个用于学习目的的Web应用程序,我有一个函数,该函数首先检查记录是否存在,然后对其进行更新,否则它将引发自定义NotFoundException。问题是当我返回Mono时,控制器抛出404错误,但是当我返回已更新的类对象时,它运行良好,并且我不想返回整个对象。
以下代码运行正常
public Mono<Application> publish(String id,boolean publish)
{
return appRepository.findById(id).flatMap( a -> {
a.setPublished(publish);
return appRepository.save(a);
}).switchIfEmpty( Mono.error(new NotFoundException("Application Not Found")));
}
及以下发生404错误的代码
public Mono<Void> publish(String id,boolean publish)
{
return appRepository.findById(id).flatMap( a -> {
a.setPublished(publish);
appRepository.save(a);
return Mono.empty().then();
}).switchIfEmpty( Mono.error(new NotFoundException("Application Not Found")));
}
我已经从ReactiveMongoRepository扩展了存储库,并且控制器类只是在调用服务函数
@PutMapping(APP_ROOT_URL + "/{id}/publish")
public Mono<Void> publish(@PathVariable("id") String id)
{
return appService.publish(id, true);
}
第一个方法不返回404,因为:
appRepository.save(a)返回保留的实体。不是一个空的单声道。因此,不会触发switchIfEmpty子句。
这来自ReactiveCrudRepository(ReactiveMongoRepository的父存储库之一)的文档
/**
* Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
* entity instance completely.
*
* @param entity must not be {@literal null}.
* @return {@link Mono} emitting the saved entity.
* @throws IllegalArgumentException in case the given {@literal entity} is {@literal null}.
*/
<S extends T> Mono<S> save(S entity);
在第二种方法中,您将明确返回空单声道。这就是为什么switchIfEmpty子句被触发的原因。
我还要指出一件事:switchIfEmpty子句放置不正确。由于findById
返回空单,如果记录没有找到一个id,switchIfEmpty
应该来之后。如果放在switchIfEmpty
之后save
,它将永远不会返回空的单声道。
所以你应该有这样的东西:
public Mono<Application> publish(String id,boolean publish)
{
return appRepository.findById(id)
.switchIfEmpty( Mono.error(new NotFoundException("Application Not Found")))
.flatMap( a -> {
a.setPublished(publish);
return appRepository.save(a);
});
}
如果您希望该方法的返回类型为,Mono<Void>
则只需执行以下操作:
public Mono<Void> publish(String id, boolean publish)
{
return appRepository.findById(id)
.switchIfEmpty( Mono.error(new NotFoundException("Application Not Found")))
.flatMap( a -> {
a.setPublished(publish);
return appRepository.save(a);
})
.then();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句