【发布时间】:2020-10-28 22:12:36
【问题描述】:
据我所知,我仍在尝试了解 WebFlux 异常的工作原理,当返回 Flux 或 Mono 中的对象时,消费者应该收到从服务器发送的相同异常。
但是,例如,当我在 Mono 中返回 HTTPException 401 时,我在消费者中收到的响应正文与我发送的不同,我读到的是 500 Internal Server 错误而不是 401。
这是我为这个问题制作的一个简单的控制器类
package com.example.demo;
import javax.xml.ws.http.HTTPException;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class Controller {
@RequestMapping(
path="/getExceptionMono",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<String> getException(){
return Mono.error(new HTTPException(401));
}
}
这里是消费者:
package com.example.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
@Component
public class ReactiveDemoConsumer implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
String url = "http://localhost:8080/getExceptionMono";
WebClient.create(url)
.get()
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class)
.subscribe(value -> System.err.println("Received String: " + value),
err -> System.err.println("Received error " + err));
}
}
这是消费者的控制台日志
Received error org.springframework.web.reactive.function.client.WebClientResponseException$InternalServerError: 500 Internal Server Error from GET http://localhost:8080/getExceptionMono
如何传递我的异常以便消费者看到我在 Mono 中传递的原始异常? 希望我的问题很清楚,提前谢谢
【问题讨论】:
-
可以使用onStatus查看响应码吗? Mono
结果 = client.get() .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON) .retrieve() .onStatus(HttpStatus::is4xxClientError, response -> ... ) .onStatus(HttpStatus::is5xxServerError, response -> ...) .bodyToMono(Person.class); -
刚刚尝试了这个建议,它只是跳过 4xx 谓词直接到 5xx,打印响应并返回“org.springframework.web.reactive.function.client.DefaultClientResponse@c7a55c43”
-
@EdenDupont 请看一遍我的回答。我希望它能澄清你的疑惑
标签: java exception mono spring-webflux flux