Spring Boot 2.0 WebClient Handle 404 перед продолжением - PullRequest
0 голосов
/ 07 мая 2018

Я хочу обработать 404 из вызова API перед продолжением конвейера. Если переданный customerId не возвращает запись, я хотел бы выдать 404, я попытался проверить stauscode внутри первой плоской карты, но карта внизу ожидает Mono, поэтому он не компилируется.

   @PostMapping(path = ["/customers/{customerId}/place"])
    fun create(@PathVariable customerId: String): Mono<ResponseEntity<OrderPlacedResponse>> {
        return webClient
                .get()
                .uri("/$customerId/cart", customerId)
                .exchange()
                .flatMap { response ->
                    response.bodyToMono(Cart::class.java)
                }
                .map { it.items.map { OrderItem(it.productId, it.quantity, it.price) } }
                .map { items -> Order(customerId, items, UUID.randomUUID().toString()) }
                .flatMap { orderRepository.save(it) }
                .map {
                    ResponseEntity.ok(OrderPlacedResponse("Order Placed", it))
                }
                .doOnError {
                    ResponseEntity
                            .status(HttpStatus.INTERNAL_SERVER_ERROR)
                            .build<OrderPlacedResponse>().toMono()
                }
    }

1 Ответ

0 голосов
/ 07 мая 2018

Ага, момент после битвы в течение часа:

 @PostMapping(path = ["/customers/{customerId}/place"])
    fun create(@PathVariable customerId: String): Mono<ResponseEntity<OrderPlacedResponse>> {
        return webClient
                .get()
                .uri("/$customerId/cart", customerId)
                .exchange()
                .flatMap { response ->
                    response.bodyToMono(Cart::class.java)
                }
                .map { it.items.map { OrderItem(it.productId, it.quantity, it.price) } }
                .map { items -> Order(customerId, items, UUID.randomUUID().toString()) }
                .flatMap { orderRepository.save(it) }
                .map {
                    ResponseEntity.ok(OrderPlacedResponse("Order Placed", it))
                }
                .switchIfEmpty(
                        ResponseEntity
                                .status(HttpStatus.NOT_FOUND)
                                .build<OrderPlacedResponse>().toMono()
                )
                .doOnError {
                    ResponseEntity
                            .status(HttpStatus.INTERNAL_SERVER_ERROR)
                            .build<OrderPlacedResponse>().toMono()
                }
    }
...