【发布时间】:2020-01-23 07:25:46
【问题描述】:
我正在使用以下代码调用远程 API 以删除用户 ID(http://localhost:8080/remove)。
try {
final RestTemplate restTemplate = new RestTemplate();
final UriComponentsBuilder builder =
UriComponentsBuilder.fromUriString(url);
builder.queryParam("acdc_id", acdcId);
ResponseEntity<ServiceResponse> result =
restTemplate.exchange(
builder.toUriString(),
HttpMethod.DELETE,
null,
ServiceResponse.class);
}catch(Exception e){
//exception handling
}
远程 API 返回 200 个 http 代码用于成功流程(工作正常),但是当某些用户 ID 不可用时,API 会在自定义响应下方发送:
{
"error code": "404",
"error": "USER ID Node not found : xyz"
}
我已经有 ServiceResponse.java 类来获得上述响应,但在这种情况下,Rest Template 返回以下错误。
org.springframework.web.client.HttpClientErrorException$NotFound: 404 null
at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:85)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:122)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:102)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:778)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:736)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:579)
我的 ServiceResponse 类是,
@JsonIgnoreProperties(ignoreUnknown = true)
public class ServiceResponse {
@JsonProperty(value = "error code")
private String errorCode;
@JsonProperty(value = "error")
private String error;
/**
* @return the error.
*/
public String getError() {
return error;
}
/**
* @param error The error to set.
*/
public void setError(final String error) {
this.error = error;
}
/**
* @return the errorCode.
*/
public String getErrorCode() {
return errorCode;
}
/**
* @param errorCode The errorCode to set.
*/
public void setErrorCode(final String errorCode) {
this.errorCode = errorCode;
}
}
您能否在这里帮助我解决我的问题,或提供任何建议,我如何从 API 获得正确的响应而不是 null 错误
【问题讨论】:
-
如果找不到用户,404就是正确答案。我问你一些澄清:你调用的 API 是否返回 404?能把两个应用的控制器的完整代码加进去吗?
-
@A.Wolf,是的,它是正确的。
-
所以您正尝试从另一个 Web 服务调用 API?您在哪里捕获结果是另一个 API,并且该 API 返回 200?
-
我不确定,但响应键不应该有空格。在您的示例中,“错误代码”中有空格。
-
是 API 在 result.getStatusCodeValue() 中返回 200 如果用户 ID 成功删除,但如果用户 ID 不可用,则返回自定义错误响应,并且由于来自 api 的自定义响应,其余模板抛出异常,而不是在 ServiceResponse 类中填充它
标签: java spring spring-boot resttemplate