使用Spring Rest Template时如何输出无法转换的消息主体。

huangapple 未分类评论57阅读模式
英文:

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&lt;DidCheckRequest&gt; requestEntity = getDidCheckRequestEntity(didName); //details not important
    //restTemplate is an instance of org.springframework.web.client.RestTemplate
    final ResponseEntity&lt;DidCheckResponse&gt; 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

huangapple
  • 本文由 发表于 2020年6月29日 16:20:31
  • 转载请务必保留本文链接:https://java.coder-hub.com/62633938.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定