[英]Spring RestTemplate handle exceptions
I am using Spring RestTemplate to make HTTP requests我正在使用 Spring RestTemplate 发出 HTTP 请求
This is my code:这是我的代码:
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;
}
In the case of a 400 response from the server I am getting an exception and my method returns null value.在来自服务器的 400 响应的情况下,我收到异常并且我的方法返回空值。
Is there any way to make Spring RestTemplate treats 400 HTTP code as 200 ?有没有办法让 Spring RestTemplate 将 400 HTTP 代码视为 200 ?
For a single place error handling use. 用于单处错误处理。 Also included import statements
还包括进口声明
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;
}
If you use a global exception handler add the below method or check this如果您使用全局异常处理程序添加以下方法或检查此
https://www.javaguides.net/2018/09/spring-boot-2-exception-handling-for-rest-apis.html add below method in GlobalExceptionHandler class 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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.