美文网首页
RestTemplate 中捕获超时异常返回自定义错误码

RestTemplate 中捕获超时异常返回自定义错误码

作者: firefly_ | 来源:发表于2020-10-29 17:29 被阅读0次
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.SocketTimeoutException;

@Configuration
@Slf4j
public class RestTemplateConfig {

    /**
     * http请求默认连接超时时间
     */
    final int DEFAULT_CONNECT_TIMEOUT = 30 * 1000;

    /**
     * http请求读数据超时时间
     */
    final int DEFAULT_READ_TIMEOUT = 30 * 1000;

    @Primary
    @Bean("restTemplate")
    public RestTemplate restTemplate() {
        RestTemplateBuilder builder = new RestTemplateBuilder();
        return builder.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
                .setReadTimeout(DEFAULT_READ_TIMEOUT)
                .build();
    }

    @Bean("appRestTemplate")
    public RestTemplate appRestTemplate() {
        RestTemplateBuilder builder = new RestTemplateBuilder();
        ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse clientHttpResponse) {
                return true;
            }

            @Override
            public void handleError(ClientHttpResponse clientHttpResponse) {
            }
        };

        ClientHttpRequestInterceptor requestInterceptor = (httpRequest, bytes, clientHttpRequestExecution) -> {
            ClientHttpResponse execute;
            try {
                execute = clientHttpRequestExecution.execute(httpRequest, bytes);
            } catch (IOException e) {
                log.info("appRestTemplate...error:" + e);
                // 特殊处理超时异常
                if (e instanceof SocketTimeoutException) {
                     // 返回自定义异常
                    // throw new AppException(AppErrorEnum.REQUEST_TIMEOUT);
                }
                throw e;
            }
            return execute;
        };
        return builder.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
                .setReadTimeout(DEFAULT_READ_TIMEOUT)
                // 自定义拦截器
                .interceptors(requestInterceptor)
                // 自定义异常处理
                .errorHandler(responseErrorHandler)
                .build();
    }

}

相关文章

网友评论

      本文标题:RestTemplate 中捕获超时异常返回自定义错误码

      本文链接:https://www.haomeiwen.com/subject/mqhlvktx.html