Spring RestTemplate invoking webservice with errors and analyze status code

前端 未结 5 922
执笔经年
执笔经年 2020-12-07 17:39

I designed a webservice to perform a task if request parameters are OK, or return 401 Unauthorized HTTP status code if request parameters are wrong or empty.

I\'m us

5条回答
  •  轮回少年
    2020-12-07 18:34

    You need to implement ResponseErrorHandler in order to intercept response code, body, and header when you get non-2xx response codes from the service using rest template. Copy all the information you need, attach it to your custom exception and throw it so that you can catch it in your test.

    public class CustomResponseErrorHandler implements ResponseErrorHandler {
    
        private ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler();
    
        public boolean hasError(ClientHttpResponse response) throws IOException {
            return errorHandler.hasError(response);
        }
    
        public void handleError(ClientHttpResponse response) throws IOException {
            String theString = IOUtils.toString(response.getBody());
            CustomException exception = new CustomException();
            Map properties = new HashMap();
            properties.put("code", response.getStatusCode().toString());
            properties.put("body", theString);
            properties.put("header", response.getHeaders());
            exception.setProperties(properties);
            throw exception;
        }
    }
    

    Now what you need to do in your test is, set this ResponseErrorHandler in RestTemplate like,

    RestTemplate restclient = new RestTemplate();
    restclient.setErrorHandler(new CustomResponseErrorHandler());
    try {
        POJO pojo = restclient.getForObject(url, POJO.class); 
    } catch (CustomException e) {
        Assert.isTrue(e.getProperties().get("body")
                        .equals("bad response"));
        Assert.isTrue(e.getProperties().get("code").equals("400"));
        Assert.isTrue(((HttpHeaders) e.getProperties().get("header"))
                        .get("fancyheader").toString().equals("[nilesh]"));
    }
    

提交回复
热议问题