簡體   English   中英

將自定義異常從 Kotlin Webclient awaitExchange Lambda function 傳遞到 web controller 的正確方法是什么?

[英]What would be the proper way to pass custom exception from Kotlin Webclient awaitExchange Lambda function to web controller?

致力於使用反應式WebClient調用另一個微服務的新微服務。

這是我所擁有的:

Controller.kts

@GetMapping(["/books/{id}"], produces = [MediaType.APPLICATION_JSON_VALUE])
suspend fun getBook(...): ResponseEntity<Any> {
   val book = service.getBook(id)
   return Response.ok().body(book)
}

服務.kts

suspend fun getBook(id: String): Any? {
   return webClient.get()
   .uri("$baseUrl")
   .accept(MediaType.APPLICATION_JSON)
   .awaitExchange { response ->
      if(response.statusCode().is4xxClientError) {
         return@awaitExchange // here is where I want to return either a custom exception as well as the status code
      }
      if(response.statusCode().is5xxServerError) {
         return@awaitExchange // similar to above but with 500 status code
      }
      return@awaitExchange response.awaitBody() // otherwise just return the body object
    }
}

一直很難弄清楚這一點以及如何將其傳遞給 controller。如果我只想返回主體,這一切都有效,但我想添加更好的異常處理。 此外,新的 spring 版本awaitExchange()已棄用,需要使用awaitExchange {} lambda fun 代替。 最后一件事,在 lambda function 中,它說“'return' is now allowed here”並希望我將其更改為return@awaitExchange...

我能夠使用onStatus(HttpStatus::is4xxClientError)將錯誤傳播到 controller 使用: Mono.error(ResponseStatusException(HttpStatus.BAD_REQUEST)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM