出现错误时如何在spring webflux中返回错误请求? [英] How to return bad request in spring webflux when there is an error?

查看:93
本文介绍了出现错误时如何在spring webflux中返回错误请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个使用 spring-webflux 的服务器端点,当 serverRequest 收到错误时,我想返回 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()) 会抛出错误.

I have this server endpoint using spring-webflux and I would like to return ServerResponse.badRequest() when the serverRequest receives a wrong parameter. The request curl -s "http://localhost:8080/4?a=5&b=3"; echo for instance, contains the right parameters. But the request curl -s "http://localhost:8080/one?a=5&b=3"; echo contains a string instead of an Integer. Then the conversion new BidRequest(Integer.parseInt(tuple2.getT1()), tuple2.getT2().toSingleValueMap()) will throw an error.

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

I was doing .onErrorReturn(new BidRequest(0, null)) but now I want to implement some operation that return ServerResponse.badRequest(). So I added in the end .onErrorResume(error -> ServerResponse.badRequest().build()) in the end, but It is not working. I also added on the place of the code .onErrorReturn() and it does not compile.

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));.

I solved based on this answer using flatmap and returning a Mono.just() or a 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());
}

这篇关于出现错误时如何在spring webflux中返回错误请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆