ResponseEntityExceptionHandler返回401异常的空响应正文

时间:2019-02-28 18:25:48

标签: java spring resttemplate

我正在尝试使用RestTemplate对身份验证服务器实施Rest调用,并记录响应,以防服务器返回异常。为了做到这一点,我使用了ResponseEntityExceptionHandler来处理HttpClientErrorException和HttpServerErrorException。

public Response sendRequest(Request requestBody, String url, HttpMethod httpMethod, Response responseBody) {
    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(requestBody.getBody(),
            this.securityHeaders);
    ResponseEntity<? extends Response> response = restTemplate.exchange(url, httpMethod, request,
            responseBody.getClass());
    return response.getBody();
}

当前我的ResponseEntityExceptionHandler是以下

@ControllerAdvice
public class RestResponseExceptionHandler extends ResponseEntityExceptionHandler {

private static Logger log = LoggerFactory.getLogger(RestResponseExceptionHandler.class);
private HttpHeaders headers = new HttpHeaders();

@ExceptionHandler(value = { HttpClientErrorException.class, HttpServerErrorException.class })
protected ResponseEntity<Object> handleConflict(HttpStatusCodeException ex, WebRequest request) {
    ErrorMessage responseBody = new ErrorMessage();
    try {
        JSONObject bodyOfException = new JSONObject(ex.getResponseBodyAsString());
        log.warn("{}| {}", ex.getStatusCode(), bodyOfException);
        responseBody.setErrorAndDescription(bodyOfException.optString("error"),
                bodyOfException.optString("error_description"));
    } catch (JSONException e) {
        log.error("{}| Bad authentication response body | Response Body | {}", ex.getStatusCode(),
                ex.getResponseBodyAsString());
    }

    return handleExceptionInternal(ex, responseBody, headers, ex.getStatusCode(), request);
}

}

但是,仅对于HttpStatus 401异常,我得到一个空的响应正文。

日志示例:

400| {"error_description":"Bad client credentials","error":"invalid_client"}

401| Bad authentication response body | Response Body | 

有人知道我如何获得401个例外的响应正文吗?

编辑: 使用邮递员呼叫身份验证服务器时,我得到非null 401 responseBody:

{
 "error": "invalid_token",
 "error_description": "Token was not recognised"
}

2 个答案:

答案 0 :(得分:1)

我终于能够记录401异常的响应正文。我添加了依赖性

  

org.apache.httpcomponents:httpclient

并配置了休息模板请求工厂

    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

显然,默认请求工厂SimpleClientHttpRequestFactory无法读取401 Http Status的响应正文。

答案 1 :(得分:0)

您为什么认为distanceMatrix = [ { 'Av. Vieira Souto, 168 - Ipanema, Rio de Janeiro - RJ, 22420-004, Brazil': 'ZERO_RESULTS' }, { 'Rynek Główny 12, 33-332 Kraków, Poland': 1540493 }, { '27 Derb Lferrane, Marrakech 40000, Morocco': 2539727 }, { 'R. Roberto Símonsen, 122 - Sé, São Paulo - SP, 01017-020, Brazil': 'ZERO_RESULTS' } ] var result = distanceMatrix.filter((item)=>{ var itemValue = parseInt(Object.values(item)[0]); return !isNaN(itemValue); }); console.log(result); 必须具有响应主体?事实并非如此。
看一下HttpStatusCodeException的构造函数,它是直接超类

RestClientResponseException

您需要预料到这种情况,并提供自定义响应正文。
实际的异常消息是作为正文的一部分返回的一个很好的值,它可能是一个复杂的对象。