【问题标题】:Spring Rest Client Exception HandlingSpring Rest 客户端异常处理
【发布时间】:2015-04-26 23:17:07
【问题描述】:

我正在使用 spring RestTemplate 来消费休息服务(暴露在 spring rest 中)。我能够消费成功场景。但是对于负面情况,服务会返回错误消息和错误代码。我需要在我的网页中显示这些错误消息。

例如对于无效请求,服务会抛出 HttpStatus.BAD_REQUEST 并带有正确的消息。如果我放置 try-catch 块,它会进入 catch 块,我无法获得 ResponseEntity 对象。

try {
    ResponseEntity<ResponseWrapper<MyEntity>> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, entity,
        new ParameterizedTypeReference<ResponseWrapper<MyEntity>>() {
    });
    responseEntity.getStatusCode();
    } catch (Exception e) {
        //TODO How to get response here, so that i can get error messages?
        e.printStackTrace();
    }

异常情况下如何获取ResponseWrapper

我从here 阅读了有关CustomRestTemplateResponseExtractor 的信息,但无法确定哪一个最适合我的情况。

【问题讨论】:

标签: java spring rest rest-client


【解决方案1】:

您可能想要区分:

HttpClientErrorException (HTTP-Status >=400) 或 HttpServerErrorException (HTTP-Status >= 500) 甚至 RestClientException

还有一个关于定义你自己的 ErrorHandler 的好文档,see this link

【讨论】:

    【解决方案2】:

    我找到了解决方案。 HttpClientErrorException 为我工作。

    它有e.getResponseBodyAsString() 函数返回ResponseBody。

    【讨论】:

      猜你喜欢
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 2011-04-18
      • 2018-12-10
      • 2019-11-09
      • 1970-01-01
      相关资源
      最近更新 更多