You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring中HttpExchange接口如何处理无响应体的404错误?

Spring HttpExchange处理404错误异常问题

我在Spring中使用HttpExchange调用外部服务时,始终无法正确处理404错误。即便404响应没有响应体,框架仍会尝试将响应体反序列化为我的领域对象,导致getUsersById方法在用户不存在时,不是返回ResponseEntity而是直接抛出异常。

我的代码实现

UsersApi接口定义

interface UsersApi {
    @HttpExchange(method = "GET", value = "/users/{id}", accept = ["application/json"])
    fun getUsersById(
        @PathVariable("id") id: String?,
    ): ResponseEntity<User?>
}

RestClient创建代理实例

val client = HttpServiceProxyFactory.builderFor(RestClientAdapter.create(restClient.build())).createClient(UsersApi::class.java)

问题细节

我无法阻止生成的代理类尝试序列化响应体,哪怕非200响应没有内容。直接使用RestClient调用toBodyLessEntity()可以得到正确的响应,显然问题出在HttpExchange生成的UsersApi实现上——它即便响应体为空,仍会调用toEntity()方法。

我原本认为这是一个Bug,但后来查到相关说明称这是预期行为,可我实在无法认同这个设计逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 05:37:33