【发布时间】:2022-06-30 13:41:05
【问题描述】:
我有一个 WebFlux 功能性 REST 端点,但由于我的代码中引发异常(例如无效路径变量上的 BadRequest),我无法返回自定义 http 错误。
考虑一下我的处理程序:
public Mono<ServerResponse> getStarships(ServerRequest request) {
String starshipType = request.pathVariable("type");
return ServerResponse
.ok()
.contentType(APPLICATION_JSON)
.body(starshipService.getFromSpacedock(starshipType), Starship.class)
.onErrorResume(InvalidStarshipTypeException.class,
e -> ServerResponse
.badRequest()
.bodyValue(e.getMessage()));
}
当starshipService.getFromSpacedock(starshipType) 返回Flux.just(new Starship()) 时,一切正常。
当它返回 Flux.error(new InvalidStarshipTypeException("invalid starship type")) 时,我希望 onErrorResume 启动并返回我的自定义 BadRequest ServerResponse 和我的消息。
相反,我的端点以 500 响应(其中包含我的自定义异常)。 onErrorResume 被忽略。
我该如何解决这个问题?
我尝试过的:
- 将异常包装在
ResponseStatusException中:我得到了400,但不是通过自定义ServerResponse 路由。这种方法的问题是我必须将 Spring 配置为在以这种方式处理异常时显示消息,这是我不希望的。 - 在 Flux 上使用 flatMap,但这会导致
Flux<ServerResponse>而不是Mono<ServerResponse>:
return starshipService.getFromSpacedock(starshipType) // remember, this is a Flux<Starship>
.flatMap(ships -> ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(ships, StarShip.class))
.onErrorResume(e -> ServerResponse.badRequest().bodyValue(e.getMessage()));
【问题讨论】:
-
I would have to add some global exception handling like you would with annotation style然后使用注释样式的端点。您已选择使用functional styled端点,它们被认为是较低级别,这意味着您可以处理自己的异常并返回自己的响应。 -
@Toerktumlare 这就是我试图使用 onErrorResume 完成的任务 - 关于为什么这不起作用的任何想法?我错过了什么?
-
您的实际问题是什么?您所写的只是这一切似乎都可以工作
It would seem that the onErrorResume, as I have put it in the code, would do the trick请更新并非常清楚,您希望它如何工作,它现在如何工作,使用什么请求,因为这不清楚。 -
@Toerktumlare 为复活节造成的延误表示歉意。我试图澄清我的问题。请注意,stackoverflow.com/questions/58429966/… 和 stackoverflow.com/questions/64578647/… 都没有回答我的问题,尽管有 reactor 和 spring 文档的链接
标签: java spring-webflux