You need to enable JavaScript to run this app. Kotlin WebClient awaitExchange Lambda如何将自定义异常传递至Web控制器
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin WebClient awaitExchange Lambda如何将自定义异常传递至Web控制器

响应式WebClient自定义异常跨层传递实现方案

核心认知误区

你遇到的lambda内return限制,仅针对普通返回值的非局部return,对主动抛出异常的逻辑无任何约束。协程上下文内的异常会自动沿着调用栈向上传播,完全不需要依赖lambda的返回值通道传递,天然支持从Service层到Controller层的跨层传递。

前置准备:自定义业务异常

先定义两个匹配错误场景的异常类,方便后续全局处理器识别:

// 下游4xx错误,携带原始返回的状态码
class DownstreamClientErrorException(
    val downstreamStatus: HttpStatusCode,
    message: String
) : RuntimeException(message)

// 下游5xx错误,对应要求返回的500状态
class DownstreamServerErrorException(message: String) : RuntimeException(message)

修正后的Service层实现

直接在awaitExchange的lambda判断分支内抛出异常即可,完全不需要用return@awaitExchange返回异常对象:

suspend fun getBook(id: String): Any? {
    return webClient.get()
        // 补全原代码遗漏的路径参数拼接,避免请求路径错误
        .uri("$baseUrl/{id}", id)
        .accept(MediaType.APPLICATION_JSON)
        .awaitExchange { response ->
            when {
                response.statusCode().is4xxClientError -> {
                    val errorMsg = response.awaitBody<String>()
                    // 直接抛出异常,throw会直接中断lambda执行,不受return限制
                    throw DownstreamClientErrorException(
                        downstreamStatus = response.statusCode(),
                        message = "下游返回客户端错误: ${response.statusCode()}, 详情: $errorMsg"
                    )
                }
                response.statusCode().is5xxServerError -> {
                    throw DownstreamServerErrorException(
                        message = "下游返回服务端错误: ${response.statusCode()}"
                    )
                }
                // 正常场景直接返回响应体,匹配原有逻辑
                else -> response.awaitBody()
            }
        }
}

关键提醒:不要把异常作为返回值通过return@awaitExchange传回上层,这种写法会把异常当成普通业务对象返回,无法触发全局异常捕获逻辑,也丢失了异常的堆栈信息。

异常处理全链路逻辑

  1. 抛出的异常会沿着协程调用栈自动向上传递,从WebClient的lambda作用域 -> Service层的suspend函数 -> Controller层的suspend方法,全程不需要手动包装传递
  2. 不需要在Controller层写冗余的try-catch,直接通过Spring的全局异常处理器统一拦截处理即可,示例如下:
@RestControllerAdvice
class GlobalExceptionHandler {
    // 统一处理下游4xx错误,透传对应状态码
    @ExceptionHandler(DownstreamClientErrorException::class)
    fun handleClientError(ex: DownstreamClientErrorException): ResponseEntity<Map<String, Any>> {
        return ResponseEntity
            .status(ex.downstreamStatus)
            .body(mapOf(
                "code" to ex.downstreamStatus.value(),
                "message" to ex.message
            ))
    }

    // 统一处理下游5xx错误,返回标准500状态
    @ExceptionHandler(DownstreamServerErrorException::class)
    fun handleServerError(ex: DownstreamServerErrorException): ResponseEntity<Map<String, Any>> {
        return ResponseEntity
            .status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body(mapOf(
                "code" to 500,
                "message" to ex.message
            ))
    }
}

注意事项

  • 原代码中构建请求URI时遗漏了id参数的拼接,实际会发起和业务预期不符的请求,需要通过uri模板变量的方式正确传参
  • 新版Spring中awaitExchange的lambda禁止非局部return,也就是不能写裸return跳出外层函数,但对throw操作无任何限制,完全符合当前场景的使用要求

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.06 00:36:02