繁体   English   中英

REST模板结果在春季启动的api调用中为空

[英]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 为成功流程返回 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 获得正确的响应而不是空错误

正如我在评论中提到的,您收到了 HttpClientErrorException,应该被捕获并处理。 您正在捕获整个 Exception 类,但其中没有代码。 或者您也可以一起使用@ControllerAdvice 和@ExceptionHandler 来实现这一点。

您可以使用 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM