[英]Spring boot - restTemplate.postForObject - params are null
[英]RestTemplate.postForObject Returns Null When ResponseEntity and Http Error Are Returned
我調用后端服務來獲取PersonResponse對象:
PersonResponse response = restTemplate.postForObject(url, request, PersonResponse.class);
PersonResponse類包含一個“狀態”字段,用於指示是否成功從后端檢索了一個人的信息:
public class PersonResponse {
private String name;
private String address;
private ResponseStatus status;
......
}
public class ResponseStatus {
private String errorCode;
private String errorMessage;
......
}
因此,當成功檢索到響應(http 200)時,我可以取回PersonResponse類型的響應。 但是,當出現錯誤(400或500)時,后端仍然會向我返回一個PersonResponse,但是只有“ status”字段中填充了錯誤信息,這就是后端如何向我返回響應:
backend code:
PersonResponse errResp = .....; // set the status field with error info
return new ResponseEntity<PersonResponse>(errResp, HttpStatus.INTERNAL_SERVER_ERROR);
但是下面的呼叫返回了一個空響應,盡管它應該給我一個PersonResponse錯誤信息。 有人可以讓我知道為什么嗎?
try {
PersonResponse response = restTemplate.postForObject(url, request, PersonResponse.class);
} catch (HttpStatusCodeException se) {
log.debug(se.getResponseBodyAsString());
// I was able to see the error information stored in PersonResponse in the log
}
return response; // always null when 500 error is thrown by the backend
請閱讀以下內容:
默認情況下,如果發生HTTP
錯誤, RestTemplate
將拋出以下exceptions
之一:
HttpClientErrorException
–如果HTTP
狀態為4xx
HttpServerErrorException
–如果HTTP
狀態為5xx
UnknownHttpStatusCodeException
–如果HTTP
狀態未知
所有這些exceptions
都是RestClientResponseException
擴展。
現在,由於您的后端響應為5xx(在您的情況下為500),因此對於您的客戶端RestTemplate
它是HttpServerErrorException
。
此外, response
你與接收HTTP 500
(INTERNAL SERVER ERROR)
狀態, RestTemplate
不會映射與POJO /反序列化回,因為它不再是一個成功( HTTP 200
)響應,即使后端包裹的errorCode和消息狀態。
因此,在您的情況下,始終為null
。
現在根據您的需求(我想從您的原始帖子中得出的信息),即使處於4xx或5xx狀態,您也要返回ResponseEntity。 您可以為各個catch
塊實現此功能,例如:
try {
PersonResponse response = restTemplate.postForObject(url, request, PersonResponse.class);
} catch (HttpStatusCodeException se) {
log.debug(se.getResponseBodyAsString());
// I was able to see the error information stored in PersonResponse in the log
// Here you have to implement to map the error with PersonResponse
ResponseStatus errorStatus = new ResponseStatus();
errorStatus.setErrorCode(HTTP500);
errorStatus.setErrorMessage(YOURMESSAGEFROMERROR);
PersonResponse responseObject = new PersonResponse();
responseObject.setResponseStatus(errorStatus);
return new ResponseEntity<PersonResponse>(responseObject,HTTPStatus.200Or500); // you can design as you need 200 or 500
} catch (HttpClientErrorException ex){
//same way for HTTP 4xx
}
另外,還有一些其他的方式就像這樣 :在您使用SpringExceptionHandler,並集中處理程序你決定如何,如果你從后台收到4XX或者5XX從客戶端響應。 最后,這完全取決於您對系統的設計方式,因為您說您無法控制后端,因此您必須根據后端響應在客戶端上實現事情。
希望這可以幫助。
您應該處理HttpClientErrorException
,還嘗試將服務返回語句更改為ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errResp)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.