赞
踩
调用第三方api 若是服务返回状态码不为200,默认会执行DefaultResponseErrorHandler 异常处理 @Override public void handleError(ClientHttpResponse response) throws IOException { HttpStatus statusCode = getHttpStatusCode(response); switch (statusCode.series()) { case CLIENT_ERROR: throw new HttpClientErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response)); case SERVER_ERROR: throw new HttpServerErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response)); default: throw new RestClientException("Unknown status code [" + statusCode + "]"); } } 判断是否异常 protected boolean hasError(HttpStatus statusCode) { return (statusCode.series() == HttpStatus.Series.CLIENT_ERROR || statusCode.series() == HttpStatus.Series.SERVER_ERROR); } 通常会直接已异常形势抛出,若不特殊处理无法获取返回提示信息。 需要捕捉HttpClientErrorException 异常,则可获取返回信息 try{ ...... }catch (HttpClientErrorException e) { String resBody = e.getResponseBodyAsString(); log.info("客户端异常返回:{}", resBody); return new ResponseEntity<>(JSON.parseObject(resBody, res), e.getStatusCode()); } 一开始我这样写,死活返回的都是null 原来跟我设置的requestFactory有关, 采用SimpleClientHttpRequestFactory 无法获取提示 需要换成 HttpComponentsClientHttpRequestFactory
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。