无法处理 HttpStatusCodeException,因为它不会抛出

问题描述 投票:0回答:1

我必须调用 API 端点 -

$apiUrl/api/users
,此时,

  • 成功创建用户 - 返回
    OK
    200
  • 用户已存在 - 返回
    CONFLICT
    409
  • ...以及一些不同的
    4xx
    状态

假设上述 API 在上述场景中运行良好。

但是,当上述端点出现

4xx
错误时,
HttpStatusCodeException
永远不会被下面的代码捕获,并且始终到达一般
Exception
。它使用 Spring
RestOperations
进行
POST
操作。

override fun signup(request: SignupRequest, token: String): SignupResponse {
    val headers = HttpHeaders()
    headers.contentType = MediaType.APPLICATION_JSON
    headers.setBearerAuth(token)

    val entity = HttpEntity(request, headers)

    try {
        return restClient.postForObject("$apiUrl/api/users", entity, SignupResponse::class.java)!!
    } catch (e: HttpStatusCodeException) {
        throw APIException(readError(e)) // never reaches here so I can throw custom exception
    } catch (e: Exception) {
        throw UnauthorizedException(HttpStatus.INTERNAL_SERVER_ERROR) // always reaches here
    }
}

我得到下面的

e: Exception
表示错误响应结构不同,但它应该已经达到
HttpStatusCodeException
才能更好地处理它???

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error:     
Instantiation of [simple type, class      
com.xxxxxxx.signup.SignupResponse] value failed for JSON property 
user_id due to missing (therefore NULL) value for creator parameter user_id which is a non-
nullable type

SignupResponse.kt
是,

data class SignupResponse(
    @JsonProperty("user_id")
    val user_id: String,
)

进一步的调试给了我一个信息,它检查

hasError()
以及可配置的
httpErrors
列表,但找不到如何配置。

还尝试过使用自定义错误处理程序,但从未达到

hasError()

class CustomResponseErrorHandler : ResponseErrorHandler {
    override fun hasError(...) { }
}

我可能还遗漏了其他东西,但提前感谢您的帮助!

java spring kotlin exception resttemplate
1个回答
0
投票

我同意@m-deinum catch,即异常与restTemplate 错误无关。相反,尝试使 SignupResponse#user_id 的类型可为空并进行检查。我相信“$apiUrl/api/users” API 没有为您提供预期的数据。

可能最好以 Map 的形式接收响应,然后构造 SignupResponse。

© www.soinside.com 2019 - 2024. All rights reserved.