CustomResponseErrorHandler.java 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. package com.ydtech.config.resttemplate;
  2. import com.ydtech.exception.SystemException;
  3. import org.springframework.http.HttpStatus;
  4. import org.springframework.http.client.ClientHttpResponse;
  5. import org.springframework.web.client.ResponseErrorHandler;
  6. import java.io.IOException;
  7. public class CustomResponseErrorHandler implements ResponseErrorHandler {
  8. @Override
  9. public boolean hasError(ClientHttpResponse response) throws IOException {
  10. int rawStatusCode = response.getRawStatusCode();
  11. return rawStatusCode > 200;
  12. }
  13. // 处理错误
  14. @Override
  15. public void handleError(ClientHttpResponse response) throws IOException {
  16. if (response.getStatusCode() == HttpStatus.REQUEST_TIMEOUT) {
  17. throw new SystemException("网络超时, 请重试!");
  18. }
  19. if (response.getStatusCode().value() > 500) {
  20. throw new SystemException("网络异常, 请重试!");
  21. }
  22. throw new SystemException("请求异常" + response.getStatusText());
  23. }
  24. }