spring-boot - 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()
}
}
解决方案
战斗了几个小时后的啊哈时刻:
@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()
}
}
推荐阅读
- django - 芹菜没有连接到redis服务器
- ios - Swift - UIView 委托协议不返回值
- javascript - 固定标题与水平滚动
- javascript - 使用来自 PHP 的查询填充 HTML 元素
- php-7 - php7 中的公共函数 __construct() -- 超出我的掌握
- javascript - 仅在打开父手风琴时显示子手风琴
- assembly - 两个寄存器的值相乘后如何得到乘积的值?
- javascript - Vanilla JS 悬停在 SVG 路径上以显示 DIV?
- laravel - Laravel 与额外数据的多对多关系
- c# - 如何使用 ASP.NET Core 标识将用户角色关联到自定义实体