SpringBoot 使用 RestTemplate 調用exchange方法 顯示錯誤信息

restTemplate調用exchange方法,若是發生錯誤,看不到服務器返回的錯誤消息。或者想依賴返回的錯誤信息進行下一步處理。html

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.nio.charset.Charset; @Configuration public class RestTemplateConfig { @Bean public RestTemplate getRestTemplate(ClientHttpRequestFactory factory) { RestTemplate restTemplate = new RestTemplate(factory); restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8"))); restTemplate.setErrorHandler(new ThrowErrorHandler()); return restTemplate; } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(10000);//單位爲ms
        factory.setConnectTimeout(5000);//單位爲ms
        return factory; } public class ThrowErrorHandler implements ResponseErrorHandler { @Override public boolean hasError(ClientHttpResponse response) throws IOException { //返回false表示無論response的status是多少都返回沒有錯 //這裏能夠本身定義那些status code你認爲是能夠拋Error
            return false; } @Override public void handleError(ClientHttpResponse response) throws IOException { System.out.println("================>" + response.getBody()); //這裏面能夠實現你本身遇到了Error進行合理的處理
 } } }
相關文章
相關標籤/搜索