简单自定义RestTemplateUtils并处理异常

RestTemplateUtils:

@Component
public class RestTemplateClientUtils {

    @Value("${request.connectTimeOut}")
    private Integer connectTimeOut;

    @Value("${request.readTimeOut}")
    private Integer readTimeOut;

    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(HttpClientBuilder.create().build());
        factory.setReadTimeout(readTimeOut);
        factory.setConnectTimeout(connectTimeOut);
        return new RestTemplate(factory);
    }

    /**
     * 通用 请求获取List
     *
     * @param url 请求地址
     * @return 数据
     */
    public <T> T requestList(String url,HttpMethod method ,ParameterizedTypeReference<T> parameterizedTypeReference) {
        try {
            ResponseEntity<T> responseEntity = restTemplate.exchange(url, method, RequestEntity.EMPTY,
                    parameterizedTypeReference);
            return  responseData(responseEntity);
        } catch (RestClientResponseException e) {
            throw new HttpException(url, "接口调用失败", e.getRawStatusCode(), e.getResponseBodyAsString());
        }
    }


    /**
     * get 请求 获取返回单个对象
     * @param url
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T get(String url, Class<T> clazz) {
        try {
            ResponseEntity<T> forEntity = restTemplate.getForEntity(url, clazz);
            return responseData(forEntity);
        } catch (RestClientResponseException e) {
            throw new HttpException(url, "接口调用失败", e.getRawStatusCode(), e.getResponseBodyAsString());
        }
    }


    /**
     * 是否为请求成功 成功返回数据 不成功返回null
     *
     * @param forEntity
     * @return
     */
    public  <T> T responseData(ResponseEntity<T> forEntity) {
        if (isSuccess(forEntity.getStatusCode())) {
            return forEntity.getBody();
        }
        return null;
    }

    /**
     * 判断是否为成功响应
     *
     * @param statusCode
     * @return
     */
    public  boolean isSuccess(HttpStatus statusCode) {
        if (statusCode.equals(HttpStatus.OK)) {
            return true;
        }
        return false;
    }
}

异常处理类`

package com.shzy.wtds.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalDisposeException {

    private final static Logger LOGGER = LoggerFactory.getLogger(GlobalDisposeException.class);

    /**
     * 全局异常处理
     *
     * @param
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultInfo handleException(Exception e) {
        LOGGER.error("系统异常:", e);
        return ResultInfoHelper.newErrorResultInfo("系统异常请联系管理员");
    }


    /**
     * http调用异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(HttpException.class)
    @ResponseBody
    public ResultInfo handleException(HttpException e) {
        LOGGER.error("信息:{} 接口:{} 响应码:{},响应内容:{} ", e.getMessage(), e.getUrl(), e.getCode(), e.getResponseContent());
        return ResultInfoHelper.newErrorResultInfo(e.getMessage());
    }
}

自定义异常类:

public class HttpException extends RestClientException {
    private String url;
    private int code;
    private String responseContent;
    public HttpException(String msg) {
        super(msg);
    }

    public HttpException(String msg, Throwable ex) {
        super(msg, ex);
    }


    public HttpException(String url, String msg,int code,String responseContent) {
        super(msg);
        this.url = url;
        this.code=code;
        this.responseContent=responseContent;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getResponseContent() {
        return responseContent;
    }

    public void setResponseContent(String responseContent) {
        this.responseContent = responseContent;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值