英文:
When using Spring Rest Template how to write out non convertable message body
问题
我正在使用Spring Rest Template,发送DidCheckRequest,并尝试将结果转换为DidCheckResponse(内容不重要),代码如下:
final HttpEntity<DidCheckRequest> requestEntity = getDidCheckRequestEntity(didName); //详细信息不重要
//restTemplate是org.springframework.web.client.RestTemplate的实例
final ResponseEntity<DidCheckResponse> responseEntity = restTemplate.postForEntity(catalogUrl, requestEntity, DidCheckResponse.class);
然而,当出现问题,例如存在错误的标头或身份验证失败时,我会收到除了200 HTTP状态以外的其他状态,并且无法将响应体转换为DidCheckResponse,会出现`org.springframework.web.client.RestClientException`,告诉我没有实际结果的转换器。我想获取返回的响应体,并将其输出。我该如何做到这一点?
英文:
I'm using Spring Rest Template and I send DidCheckRequest and try to convert the result to DidCheckResponse (content is not important) like this:
final HttpEntity<DidCheckRequest> requestEntity = getDidCheckRequestEntity(didName); //details not important
//restTemplate is an instance of org.springframework.web.client.RestTemplate
final ResponseEntity<DidCheckResponse> responseEntity = restTemplate.postForEntity(catalogUrl, requestEntity, DidCheckResponse.class);
However, when something goes wrong, like I have some bad header or there is an authentication failure, I get other than 200 HTTP Status and the body is can not be converted to DidCheckResponse and I get the org.springframework.web.client.RestClientException
, which tells me, that I have no converter for the actual result. I would like to get the returned body, which I would like to write out. How can I do that?
答案1
得分: 0
当出现问题时,实际上状态码不应为200。只有在收到成功响应时,才使用状态码200。
对于其他情况,应有一个不同的响应类,一个通用的错误响应类来处理转换问题。
您可以参考下面的链接。
https://www.baeldung.com/spring-rest-template-error-handling
英文:
When something is wrong, it should not be 200 actually. 200 status code is only meant when you receive a successful response.
For other than 200, have a different Response class, a generic error response class to handle the conversion problem.
You can refer below.
https://www.baeldung.com/spring-rest-template-error-handling
专注分享java语言的经验与见解,让所有开发者获益!
评论