springboot中restTemplate请求时的异常处理以及编码格式

2023年2月15日11:58:57
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Bean
    public RestTemplate getRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        //设置restTemplate的默认异常处理器为自定义的处理器
        restTemplate.setErrorHandler(new CustomErrorHandler());
        //修改restTemplate默认编码格式为UTF-8
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        for (int i = 0; i < messageConverters.size(); i++) {
            HttpMessageConverter<?> messageConverter = messageConverters.get(i);
            if (messageConverter.getClass().equals(StringHttpMessageConverter.class)) {
                messageConverters.set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
            }
        }
        return restTemplate;
    }
}

自定义restTemplate异常处理器,需要实现ResponseErrorHandler 接口

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;
import java.net.URI;

public class CustomErrorHandler implements ResponseErrorHandler {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 表示 response 是否存在任何错误。实现类通常会检查 response 的 HttpStatus。
     *
     * @param response
     * @return
     * @throws IOException
     */
    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        int rawStatusCode = response.getRawStatusCode();
        HttpStatus statusCode = HttpStatus.resolve(rawStatusCode);
        return (statusCode != null ? statusCode.isError() : hasError(rawStatusCode));
    }

    protected boolean hasError(int unknownStatusCode) {
        HttpStatus.Series series = HttpStatus.Series.resolve(unknownStatusCode);
        return (series == HttpStatus.Series.CLIENT_ERROR || series == HttpStatus.Series.SERVER_ERROR);
    }

    /**
     * 处理 response 中的错误, 当 hasError 返回 true 时才调用此方法。
     * 当返回异常信息时自己想要做的一些操作处理
     *
     * @param response
     * @throws IOException
     */
    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
    }

    /**
     * 覆盖了上面的方法
     * 处理 response 中的错误, 当 hasError 返回 true 时才调用此方法。
     * 当返回异常信息时自己想要做的一些操作处理
     *
     * @param url
     * @param method
     * @param response
     * @throws IOException
     */
    @Override
    public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
        logger.error("=======================ERROR============================");
        logger.error("HOST:{},URI:{}", url.getHost(), url.getPath());
        logger.error("Method Type:{}", method.name());
        logger.error("Exception:{}", response.getStatusCode());
        logger.error("========================================================");
    }
}

  • 作者:Anhk丶
  • 原文链接:https://blog.csdn.net/qq_45829350/article/details/111831942
    更新时间:2023年2月15日11:58:57 ,共 2825 字。