【问题标题】:Springboot ExceptionHandler catch from Client来自客户端的 Spring Boot ExceptionHandler 捕获
【发布时间】:2017-12-30 04:15:56
【问题描述】:

我开发了一个 Spring Boot 项目,我使用 ExceptionHandler 来捕获带有 @RestControllerAdvice 注释的所有异常。 服务器端捕获异常没有问题。 但是,我不知道如何在客户端应用程序中捕获这些异常。

你能帮帮我吗?

【问题讨论】:

  • 你用的是什么客户端?休息模板?
  • 是的,它是 RestTemplate
  • 然后在使用 RestTemplate 时使用 try - catch 块。捕获 RestClientException 并根据需要进行处理。
  • 谢谢 Gondy,它会工作的 :)

标签: rest spring-boot exception-handling


【解决方案1】:

如果您使用的是spring-web 的RestTemplate,下面是一个示例:

try {
    ResponseEntity<String> response = new RestTemplate().getForEntity(url, String.class);
    System.out.println("Response: " + response.getBody());
} catch (HttpStatusCodeException e) {
    System.err.println("Problem querying " + url + ". " + 
        "Status code " + e.getStatusCode() + 
        " and error message " + e.getResponseBodyAsString());
}

注意RestTemplate对于错误状态码默认会抛出异常,所以需要捕捉HttpStatusCodeException。

虽然并非所有错误都是HttpStatusCodeException,但所有错误都以RestClientException 作为父级,如果确实需要,您也可以捕获它。

【讨论】:

    【解决方案2】:

    在客户端,您可能正在使用 HTTP 客户端(例如 Spring 的 RestTemplate 或 Apache Commons 的 HttpClient)。可能是这样的:

    ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
    

    鉴于此代码,HTTP 状态和响应正文如下所示:

    HttpStatus httpStatus = response.getStatusCode(); 
    String responseBody = response.getBody();
    

    因此,您通过 RestControllerAdvice 提供的任何状态代码和响应正文都可以从响应中读出。

    一种典型的方法是评估 HttpStatus 是否为 200,如果不是则落入异常处理块,使用响应正文了解异常的性质。

    【讨论】:

    • 感谢 Glitch,您的解决方案节省了我的时间。
    猜你喜欢
    • 2016-12-16
    • 2020-06-05
    • 1970-01-01
    • 2015-08-26
    • 2022-11-28
    • 1970-01-01
    • 2013-01-03
    • 2019-06-29
    • 2018-08-22
    相关资源
    最近更新 更多