【问题标题】:RestApi exception with response带有响应的 Rest Api 异常
【发布时间】:2017-01-17 19:14:19
【问题描述】:

我正在使用 RestTemplate 来处理我们的服务和 polycom rmx 设备之间的通信,该设备具有一个 http api,主要由来回传输 xml 的 post 调用组成。当出现错误(即未找到的东西)时,问题就出现了,它不会返回预期的响应,所以我得到一个错误

org.springframework.http.converter.HttpMessageNotReadableException: 无法解组为 [class com.ourclass.polycom.rmx.sdk.RESPONSETRANSRES]:意外 元素(uri:“”,本地:“RESPONSE_GENERAL”)。预期的元素是 ,

所以它会将错误对象反序列化为 RESPONSETRANSRES,因为这是传入的内容(请参见下面的代码),但是由于错误响应,我们实际上得到了一个 RESPONSEGENERAL 对象,因此它不知道如何编组。

protected <Request, Response> Response doPost(String uri, Request data, Class<Response> responseClass) throws Exception
    {
        String requestUrl = null;
        try
        {
            RestTemplate restApi = obtainRestTemlate(true);
            ResponseEntity<Response> response = restApi.exchange(requestUrl, HttpMethod.POST, createRestRequest(HttpMethod.POST, uri, data), responseClass);
            validateResponseStatus(response.getStatusCode());
            return response.getBody();
        }
        catch (Exception e)
        {
            throw translateError(requestUrl, e);
        }
    }

由于这是针对错误情况,我更愿意捕获异常,获取有效负载并将其重新解析为我知道的对象。这可能吗?如何实现?

我正在查看this SO 答案,但e.getResponseBodyAsString(); 不是我的例外成员。可能还需要注意的是,当错误发生时,状态码仍然是 200 ok。所以帖子中指出的问题不会发生在我身上。

【问题讨论】:

标签: java spring


【解决方案1】:

不是最好的解决方案,也是一种 hack 我将其作为字符串返回,而不是尝试手动将其编组为预期响应,并在出错时将其编组为另一个对象。

    Class<?> requestClass = data.getClass();
    Method method = requestClass.getMethod("setTRANSCOMMONPARAMS", TransCommonParamsContent.class);
    TransCommonParamsContent newTransCommonParams = new TransCommonParamsContent();
    newTransCommonParams.setMCUTOKEN(transCommonParamsContent.getMCUTOKEN());
    newTransCommonParams.setMCUUSERTOKEN(transCommonParamsContent.getMCUUSERTOKEN());
    method.invoke(data, newTransCommonParams);

    String responseString = doPost(getBaseUri(), data, String.class);
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(responseClass);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        @SuppressWarnings("unchecked")
        Response response = (Response) unmarshaller.unmarshal(new StringReader(responseString));
        return response;
    } catch (Exception e) {
        JAXBContext jaxbContext = JAXBContext.newInstance(RESPONSEGENERAL.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        RESPONSEGENERAL errorResponse = (RESPONSEGENERAL) unmarshaller.unmarshal(new StringReader(responseString));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 2020-04-01
    相关资源
    最近更新 更多