【问题标题】:Spring Boot 2.0 WebClient Handle 404 before continuingSpring Boot 2.0 WebClient 在继续之前处理 404
【发布时间】:2018-10-17 06:36:14
【问题描述】:

我想在继续管道之前处理来自 API 调用的 404。如果传入的 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()
                }
    }

【问题讨论】:

    标签: spring-boot kotlin spring-webflux


    【解决方案1】:

    战斗了几个小时后的啊哈时刻:

     @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()
                    }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2020-10-10
      • 2018-08-18
      相关资源
      最近更新 更多