Spring WebClient 根据响应主体抛出错误

sal*_*ndu 1 spring spring-webflux spring-webclient

我正在使用 Spring WebClient 调用 REST API。我想根据响应抛出错误。例如,如果 body 出现错误 (400)

{"error": "error message1 "}
Run Code Online (Sandbox Code Playgroud)

然后我想抛出一个带有“error message1”的错误。如果主体有错误(400),则同样的方法

{"error_code": "100020"}
Run Code Online (Sandbox Code Playgroud)

然后我想抛出一个 error_cde 100020 的错误。我想以非阻塞的方式做到这一点。

public Mono<Response> webclient1(...) {

 webClient.post().uri(createUserUri).header(CONTENT_TYPE, APPLICATION_JSON)
                .body(Mono.just(request), Request.class).retrieve()
                .onStatus(HttpStatus::isError, clientResponse -> {
        
                 //Error Handling
                
                }).bodyToMono(Response.class);
}
Run Code Online (Sandbox Code Playgroud)

saw*_*wim 5

应以反应方式提取 ClientResponse 中的主体 ( javadoc ),并且方法中的 lambdaonStatus应返回另一个主体Mono( javadoc )。总结一下,看看下面的例子

onStatus(HttpStatus::isError, response -> response
    .bodyToMono(Map.class)
    .flatMap(body -> {
        var message = body.toString(); // here you should probably use some JSON mapper
        return Mono.error(new Exception(message));
    })
);
Run Code Online (Sandbox Code Playgroud)