【问题标题】:Spring RestTemplate handle exceptionsSpring RestTemplate 处理异常
【发布时间】:2019-06-02 08:19:40
【问题描述】:

我正在使用 Spring RestTemplate 发出 HTTP 请求

这是我的代码:

public static ResponseEntity<String> makeRequest() {
    ResponseEntity<String> response = null;
    try {
         RestTemplate restTemplate = new RestTemplate();
         response = restTemplate.exchange(URI, HttpMethod.GET, null, 
         String.class);

     }catch (HttpStatusCodeException e) {
         System.out.println(e.getStatusCode());
     }catch (Exception e) {
         e.printStackTrace();
     }
         return response;
}

对于来自服务器的 400 响应,我得到一个异常并且我的方法返回 null 值。

有没有办法让 Spring RestTemplate 将 400 HTTP 代码视为 200 ?

【问题讨论】:

  • “有什么方法可以让 Spring RestTemplate 将 400 HTTP 代码视为 200”是什么意思。你想达到什么目的?
  • 您正在捕获异常,然后选择返回 null。你想要发生什么? (您不能“将 400 视为 200”,因为它们不一样,但如果您解释在 200 的情况下您希望发生什么,那么也许我们可以提供帮助。)
  • Spring RestTemplate 将 400 HTTP 代码视为异常,因此我的响应变量为空,我的客户端无法获取 Http 代码和消息代码以了解究竟发生了什么。如果是 200,我的响应不为空,所以我可以这样做:response.getBody(); response.getStatusCode();

标签: java spring rest spring-web


【解决方案1】:

供单一地方错误处理使用。还包括导入语句

import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

RestTemplate restTemplate() {
    SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
    clientHttpRequestFactory.setConnectTimeout(2000);
    clientHttpRequestFactory.setReadTimeout(3000);
    RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override public boolean hasError(ClientHttpResponse response)
                throws IOException {
            try {
                //Do your stuff
                return super.hasError(response);
            } catch (Exception e) {
                logger.error("Exception [" + e.getMessage() + "] occurred while trying to send the request", e);
                return true;
            }
        }

        @Override public void handleError(ClientHttpResponse response)
                throws IOException {
            try {
                //Do your stuff
                super.handleError(response);
            } catch (Exception e) {
                logger.error("Exception [" + e.getMessage() + "] occurred while trying to send the request", e);
                throw e;
            }
        }
    });



    return restTemplate;
}

【讨论】:

    【解决方案2】:

    如果您使用全局异常处理程序,请添加以下方法或检查此

    https://www.javaguides.net/2018/09/spring-boot-2-exception-handling-for-rest-apis.html 在 GlobalExceptionHandler 类中添加下面的方法

    @ExceptionHandler({HttpClientErrorException.class, HttpStatusCodeException.class, HttpServerErrorException.class})
        @ResponseBody
        public ResponseEntity<Object> httpClientErrorException(HttpStatusCodeException e) throws IOException {
            BodyBuilder bodyBuilder = ResponseEntity.status(e.getRawStatusCode()).header("X-Backend-Status", String.valueOf(e.getRawStatusCode()));
            if (e.getResponseHeaders().getContentType() != null) {
                bodyBuilder.contentType(e.getResponseHeaders().getContentType());
            }
            return bodyBuilder.body(e.getResponseBodyAsString());
        }
    

    【讨论】:

      猜你喜欢
      • 2016-10-31
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2015-07-17
      • 2023-03-28
      • 2017-01-27
      相关资源
      最近更新 更多