如果发生错误,我希望以下方法引发自定义异常:
@Service
public class MyClass {
private final WebClient webClient;
public MatcherClient(@Value("${my.url}") final String myUrl) {
this.webClient = WebClient.create(myUrl);
}
public void sendAsync(String request) {
Mono<MyCustomResponse> result = webClient.post()
.header(HttpHeaders.CONTENT_TYPE, "application/json")
.body(BodyInserters.fromObject(request))
.retrieve()
.doOnError(throwable -> throw new CustomException(throwable.getMessage()))
.subscribe(response -> log.info(response));
}
}
我还设置了一个单元测试,期望抛出 CustomException。不幸的是,测试失败了,异常被包裹在一个 Mono 对象中。这里还有测试代码供参考:
@Test(expected = CustomException.class)
public void testSendAsyncRethrowingException() {
MockResponse mockResponse = new MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.setResponseCode(500).setBody("Server error");
mockWebServer.enqueue(mockResponse);
matcherService.matchAsync(track);
}
我正在使用MockWebServer来模拟测试中的错误。
那么,如果调用,我应该如何实现 doOnError 或 onError 部分,以使我的方法真正抛出异常?