【发布时间】:2019-07-17 12:55:45
【问题描述】:
我正在编写一个复杂的应用程序作为 Spring 5 Webflux 的实验。我打算在这个应用程序中使用很多技术。我熟悉“旧式”@RestController,但现在,我正在编写函数式端点。例如。公司注册服务的后端。我在“旧世界”中追求类似@ControllerAdvice 的东西。但我真的找不到任何类似的反应式等价物。 (或者任何对我有用的东西。)
我有一个非常基本的设置。一个路由功能、一个反应式 Cassandra 存储库、一个处理程序和一个测试类。存储库操作可能会抛出 IllegalArgumentException,我想通过向客户端返回 HTTP 状态 BadRequest 来处理它。只是作为我有能力做到的一个例子。 :-) 异常由处理程序类处理。这是我的代码。
路由器配置
@Slf4j
@Configuration
@EnableWebFlux
public class RouterConfig {
@Bean
public RouterFunction<ServerResponse> route(@Autowired CompanyHandler handler) {
return RouterFunctions.route()
.nest(path("/company"), bc -> bc
.GET("/{id}", handler::handleGetCompanyDataRequest)
.before(request -> {
log.info("Request={} has been received.", request.toString());
return request;
})
.after((request, response) -> {
log.info("Response={} has been sent.", response.toString());
return response;
}))
.build();
}
}
CompanyHandler
@Slf4j
@Component
public class CompanyHandler {
@Autowired
private ReactiveCompanyRepository repository;
// Handle get single company data request
public Mono<ServerResponse> handleGetCompanyDataRequest(ServerRequest request) {
//Some validation ges here
return repository.findById(Mono.just(uuid))
.flatMap(this::ok)
.onErrorResume(IllegalArgumentException.class, e -> ServerResponse.badRequest().build())
.switchIfEmpty(ServerResponse.notFound().build());
}
private Mono<ServerResponse> ok (Company c) {
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromPublisher(Mono.just(c), Company.class));
}
}
ReactiveCompanyRepository
@Component
public interface ReactiveCompanyRepository extends ReactiveCassandraRepository<Company, UUID>{
Mono<Company> findByName(String name);
Mono<Company> findByEmail(String email);
}
我的问题是 .onErrorResume(IllegalArgumentException.class, e -> ServerResponse.badRequest().build()) 从未被调用,并且在测试用例中:
@SuppressWarnings("unchecked")
@Test
public void testGetCompanyExceptionDuringFind() {
Mockito.when(repository.findById(Mockito.any(Mono.class))).thenThrow(new IllegalArgumentException("Hahaha"));
WebTestClient.bindToRouterFunction(routerConfig.route(companyHandler))
.build()
.get().uri("/company/2b851f10-356e-11e9-a847-0f89e1aa5554")
.accept(MediaType.APPLICATION_JSON_UTF8)
.exchange()
.expectStatus().isBadRequest()
.returnResult(Company.class)
.getResponseBody();
}
我总是得到 HttpStatus 500 而不是 400。所以它失败了。任何帮助将不胜感激!
【问题讨论】:
标签: spring exception-handling spring-webflux