使用RestTemplate调用API时如何捕获超时异常

时间:2019-05-06 03:01:19

标签: java spring-boot resttemplate

我有函数调用api,请使用RestTemplate。我想在超时将返回null时捕获异常,这是我的代码:

//Create resttemplate
public List<String> getRoleUser(String username) {
    try{
        RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
        String[] list = restTemplate.getForObject("(link call api)", String[].class);
        return Arrays.asList(list);
    }catch (Exception ex){
        ex.printStackTrace();
        return null;
    }
}

//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory()
{
    SimpleClientHttpRequestFactory clientHttpRequestFactory
                      = new SimpleClientHttpRequestFactory();
    //Connect timeout
    clientHttpRequestFactory.setConnectTimeout(10_000);

    //Read timeout
    clientHttpRequestFactory.setReadTimeout(10_000);
    return clientHttpRequestFactory;
}

但是它不起作用。 那么,超时后如何返回null?

2 个答案:

答案 0 :(得分:0)

您应该捕获HttpStatusCodeException异常:

try {
    restTemplate.exchange(...);
} catch (HttpStatusCodeException exception) {
    int statusCode = exception.getStatusCode().value();
    ...
}

答案 1 :(得分:0)

我解决了这个问题。调用API后,我再次检查RestTemplate的值返回。这段代码:

public List<String> getRoleUser(String username) {
        try {
            RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
            String[] list = restTemplate.getForObject("link call api",
                    String[].class);
            if (list.length > 0) {
                return Arrays.asList(list);
            }
            return null;
        } catch (Exception exception) {
            return null;
        }
    }