Spring RestTemplate处理异常

4
我将使用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?你想达到什么目的?” - akortex
1
你捕获了异常,然后选择返回null。相反你想要发生什么?(你不能“将400视为200”因为它们不同,但如果您解释一下在200的情况下您想要发生什么,那么也许我们可以帮助您。) - chrylis -cautiouslyoptimistic-
Spring RestTemplate将400 HTTP代码视为异常,因此我的响应变量为空,我的客户端无法获取HTTP代码和消息代码以了解发生了什么。在200的情况下,我的响应不为空,所以我可以这样做:response.getBody(); response.getStatusCode(); - Zak FST
2个回答

4

针对单个位置的错误处理。还包括导入语句。

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;
}

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

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());
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接