何时引发HttpStatusCodeException异常?

Nag*_*Raj -3 java rest spring httpexception

当我使用下面的代码时,出现HttpStatusCodeException异常的情况是什么?

ResponseEntity<Object> response = 
  restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, entity, Object.class);
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮忙吗????????

vsk*_*hul 8

spring-web 库中org.springframework.web.client.RestTemplate添加了类的 exhange(...) 方法。3.1.0.RELEASE

此方法抛出RestClientException涵盖客户端 (4_xx) 和服务器 (5_xx) 端 http 代码错误。但RestClientException不提供getStatusCode(), getResponseAsString()等等...方法。

  1. HttpsStatusCodeException是其子代,RestClientException 它正在做同样的事情,但使用了诸如getStatusCode(), getResponseAsString()等的附加方法。

  2. HttpClientErrorException的子级HttpsStatusCodeException并且仅接受客户端错误(4_xx)而不是服务器错误。

  3. HttpServerErrorException的子级HttpsStatusCodeException并且仅接收服务器错误(5_xx)而不是客户端错误。


gto*_*sto 5

根据文件有两种类型的HttpStatusCodeException HttpClientErrorExceptionHttpServerErrorException

  • 收到HTTP 4xx时将抛出前者。
  • 收到HTTP 5xx时将抛出后者。

因此您可以仅使用ResponseEntity.BodyBuilder.status(505)例如HttpServerErrorException