当 Flux 为空时返回 404

Ran*_*dom 4 project-reactor spring-webflux

当 Flux 为空时,我试图返回 404,类似于此处:WebFlux 功能:如何检测空 Flux 并返回 404?

我主要担心的是,当您检查通量是否包含元素时,它会发出该值,而您会丢失它。当我尝试在服务器响应上使用 switch if empty 时,它永远不会被调用(我偷偷认为这是因为 Mono 不是空的,只有主体是空的)。

我正在做的一些代码(我的路由器类上有一个过滤器,检查 DataNotFoundException 以返回 notFound):

Flux<Location> response = this.locationService.searchLocations(searchFields, pageToken);
return ok()
        .contentType(APPLICATION_STREAM_JSON)
        .body(response, Location.class)
        .switchIfEmpty(Mono.error(new DataNotFoundException("The data you seek is not here.")));
Run Code Online (Sandbox Code Playgroud)

^这从不调用 switchIfEmpty

Flux<Location> response = this.locationService.searchLocations(searchFields, pageToken);

return response.hasElements().flatMap(l ->{
   if(l){
       return ok()
               .contentType(APPLICATION_STREAM_JSON)
               .body(response, Location.class);
   } 
   else{
       return Mono.error(new DataNotFoundException("The data you seek is not here."));
   }
});
Run Code Online (Sandbox Code Playgroud)

^这会丢失 hasElements 上的发射元素。

有没有办法在 hasElements 中恢复发出的元素,或者让 switchIfEmpty 只检查主体的内容?

Ale*_*kin 7

您可以将switchIfEmpty运算符应用于您的Flux<Location> response.

Flux<Location> response = this.locationService
        .searchLocations(searchFields, pageToken)
        .switchIfEmpty(Mono.error(new DataNotFoundException("The data you seek is not here.")));
Run Code Online (Sandbox Code Playgroud)


小智 5

虽然发布的答案确实是正确的,但如果您只想返回状态代码(加上原因)并且不想摆弄任何自定义过滤器或定义自己的错误响应异常,则有一个方便的异常类。

另一个好处是,您不必将响应包装在任何 ResponseEntity 对象内,虽然对于某些情况很有用(例如,使用位置 URI 创建),但对于简单的状态响应来说有点过分了。

另请参阅https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/server/ResponseStatusException.html

 return this.locationService.searchLocations(searchFields, pageToken)
        .buffer()
        .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND, "these are not the droids you are lookig for")));
Run Code Online (Sandbox Code Playgroud)