spring 引导中的 api 调用中的 Rest 模板结果为空

Rest template result is getting null in api call in spring boot

我正在使用以下代码调用远程 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 return 成功流程的 200 个 http 代码(工作正常),但是当某些用户 ID 不可用时 API 发送以下自定义响应:

{
"error code": "404",
"error": "USER ID Node not found : xyz"
} 

我已经 ServiceResponse.java class 获得以上响应,但在这种情况下 Rest Template return 低于错误。

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) 

我的服务响应 class 是,

@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 错误

您可以使用 Controller Advice @ControllerAdvice 注释来处理异常。您可以从该方法发送自定义响应。您可以为 HttpClientErrorException 定义 exceptionHandler 并从此方法发送自定义响应。

请检查 https://www.tutorialspoint.com/spring_boot/spring_boot_exception_handling.htm 了解更多详情。

另一种选择是您可以使用如下所示的 CustomResponseErrorHandler

@Component
public class RestTemplateResponseErrorHandler 
  implements ResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse httpResponse) 
      throws IOException {

        return (
          httpResponse.getStatusCode().series() == CLIENT_ERROR 
          || httpResponse.getStatusCode().series() == SERVER_ERROR);
    }

    @Override
    public void handleError(ClientHttpResponse httpResponse) 
      throws IOException {

        if (httpResponse.getStatusCode()
          .series() == HttpStatus.Series.SERVER_ERROR) {
            // handle SERVER_ERROR
        } else if (httpResponse.getStatusCode()
          .series() == HttpStatus.Series.CLIENT_ERROR) {
            // handle CLIENT_ERROR
            if (httpResponse.getStatusCode() == HttpStatus.NOT_FOUND) {
                throw new NotFoundException();
            }
        }
    }
}

然后像这样使用它

@Bean
    RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());

        return restTemplate;
    }

请检查 https://www.baeldung.com/spring-rest-template-error-handling 是否有 ResponseErrorHandler

正如我在 中提到的,您收到了 HttpClientErrorException,应该捕获并处理它。您捕获了整个异常 class,但其中没有代码。或者您也可以同时使用@ControllerAdvice 和@ExceptionHandler 来实现这一点。