return bad request in spring webflux 出现错误时如何处理?

How to return bad request in spring webflux when there is an error?

我有这个服务器端点使用 spring-webflux,当 serverRequest 接收到错误参数时,我想 return ServerResponse.badRequest()。例如,请求 curl -s "http://localhost:8080/4?a=5&b=3"; echo 包含正确的参数。但是请求 curl -s "http://localhost:8080/one?a=5&b=3"; echo 包含一个字符串而不是一个整数。然后转换new BidRequest(Integer.parseInt(tuple2.getT1()), tuple2.getT2().toSingleValueMap())会报错

我在做 .onErrorReturn(new BidRequest(0, null)) 但现在我想实现一些 return ServerResponse.badRequest() 的操作。所以我在最后添加了.onErrorResume(error -> ServerResponse.badRequest().build()),但是它不起作用。我还在代码 .onErrorReturn() 的位置添加了它,但它无法编译。

public Mono<ServerResponse> bidRequest(ServerRequest serverRequest) {
    var adId = serverRequest.pathVariable("id");
    var attributes = serverRequest.queryParams();
    log.info("received bid request with adID: {} attributes: {}", adId, attributes);

    return Mono.just(Tuples.of(adId, attributes))
        .map(tuple2 -> new BidRequest(Integer.parseInt(tuple2.getT1()), tuple2.getT2().toSingleValueMap()))
        // I WANT TO REPLACE IT FOR A BAD REQUEST
        // .onErrorReturn(new BidRequest(0, null))
        .flatMap(bidRequest -> {
            return Flux.fromStream(bidderService.bidResponseStream(bidRequest))
                    .flatMap(this::gatherResponses)
                    .reduce((bidResp1, bidResp2) -> {
                        if (bidResp1.getBid() > bidResp2.getBid()) return bidResp1;
                        else return bidResp2;
                    });
        })
        .map(bid -> {
            var price = bid.getContent().replace("$price$", bid.getBid().toString());
            bid.setContent(price);
            return bid;
        })
        .flatMap(winner -> {
            return ServerResponse.ok()
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromValue(winner.getContent()));
        })
        .switchIfEmpty(ServerResponse.notFound().build())
        // THIS DOES NOT RETURN ANY BAD REQUEST
        .onErrorResume(error -> ServerResponse.badRequest().build());
}

我基于 this answer 使用 flatmap 解决并返回 Mono.just()Mono.error(new ResponseStatusException(HttpStatus.BAD_REQUEST));

return Mono
        .just(Tuples.of(adId, attributes))
        .flatMap(tuple2 -> {
            if (validate(tuple2)) {
                log.info("request parameters valid: {}", tuple2);
                return Mono.just(new BidRequest(Integer.parseInt(tuple2.getT1()), tuple2.getT2().toSingleValueMap()));
            } else {
                log.error("request parameters invalid: {}", tuple2);
                return Mono.error(new ResponseStatusException(HttpStatus.BAD_REQUEST));
            }
        })
        .flatMap(....
private boolean validate(Tuple2<String, MultiValueMap<String, String>> tuple2) {
    return GenericValidator.isInteger(tuple2.getT1());
}