首页 > 解决方案 > Spring Boot 2.0 WebClient 在继续之前处理 404

问题描述

我想在继续管道之前处理来自 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-bootkotlinspring-webflux

解决方案


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

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

推荐阅读