简体   繁体   English

使用 RestTemplate getForObject 时无法捕获错误

[英]Unable to catch error when using RestTemplate getForObject

I'm using RestTemplate to call my webservice's health actuator endpoint from another webservice of mine to see if the webservice is up.我正在使用 RestTemplate 从我的另一个 Web 服务调用我的 Web 服务的运行状况执行器端点,以查看 Web 服务是否已启动。 If the webservice is up, all works fine, but when it's down, I get an error 500, "Internal Server Error".如果 web 服务启动,一切正常,但当它关闭时,我收到错误 500,“内部服务器错误”。 If my webservice is down, I'm trying to catch that error to be able to handle it, but the problem I'm having is that I can't seem to be able to catch the error.如果我的网络服务已关闭,我会尝试捕获该错误以便能够处理它,但我遇到的问题是我似乎无法捕获该错误。

I've tried the following and it never enters either of my catch sections我尝试了以下方法,但它从未进入我的任何一个捕获部分

@Service
public class DepositService {

  @Bean
  public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder
            .setConnectTimeout(Duration.ofMillis(3000))
            .setReadTimeout(Duration.ofMillis(3000))
            .build();
  }

  private static void getBankAccountConnectorHealth() {
    final String uri = "http://localhost:9996/health";

    RestTemplate restTemplate = new RestTemplate();

    String result = null;

    try {
      result = restTemplate.getForObject(uri, String.class);
    } catch (HttpClientErrorException exception) {
      System.out.println("callToRestService Error :" + exception.getResponseBodyAsString());
    } catch (HttpStatusCodeException exception) {
      System.out.println( "callToRestService Error :" + exception.getResponseBodyAsString());
    }

    System.out.println(result);
  }

}

I've also tried doing it this way, but same results.我也试过这样做,但结果相同。 It never seems to enter my error handler class.它似乎永远不会进入我的错误处理程序 class。

public class NotFoundException extends RuntimeException {
}

public class RestTemplateResponseErrorHandler implements ResponseErrorHandler {

  @Override
  public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
    return (httpResponse.getStatusCode().series() == CLIENT_ERROR || httpResponse.getStatusCode().series() == SERVER_ERROR);
  }

  @Override
  public void handleError(ClientHttpResponse httpResponse) throws IOException {
    if (httpResponse.getStatusCode().series() == HttpStatus.Series.SERVER_ERROR) {
      // handle SERVER_ERROR
      System.out.println("Server error!");
    } else if (httpResponse.getStatusCode().series() == HttpStatus.Series.CLIENT_ERROR) {
      // handle CLIENT_ERROR
      System.out.println("Client error!");

      if (httpResponse.getStatusCode() == HttpStatus.NOT_FOUND) {
        throw new NotFoundException();
      }
    }
  }



}

@Service
public class DepositService {

  @Bean
  public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder
            .setConnectTimeout(Duration.ofMillis(3000))
            .setReadTimeout(Duration.ofMillis(3000))
            .build();
  }

  private static void getAccountHealth() {
    final String uri = "http://localhost:9996/health";

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());

    String result = null;

    result = restTemplate.getForObject(uri, String.class);

    System.out.println(result);
  }

}

Any suggestions as to how I can call my webservice's health actuator from another webservice and catch if that webservice is down?关于如何从另一个 Web 服务调用我的 Web 服务的健康执行器并捕获该 Web 服务是否关闭的任何建议?

It looks like the getForObject doesn't throw either of the exceptions you are catching.看起来getForObject不会抛出您正在捕获的任何异常。 From the documentation , it throws RestClientException .文档中,它抛出RestClientException The best method I have found for identifying thrown exceptions is to catch Exception in the debugger and inspect it to find out if it's useful.我发现识别抛出异常的最佳方法是在调试器中捕获Exception并检查它以确定它是否有用。

With the second method, I'm not sure why you would create a bean method for the RestTemplate and then create one with new .使用第二种方法,我不确定为什么要为RestTemplate创建一个 bean 方法,然后使用new创建一个。 You probably should inject your RestTemplate and initialise the ResponseErrorHandler with the RestTemplateBuilder::errorHandler method.您可能应该注入您的RestTemplate并使用RestTemplateBuilder::errorHandler方法初始化ResponseErrorHandler

Internal serve error throw HttpServerErrorException You should catch this exception if you want to handle it However the better way to do that is using error handler you can see the following posts to see how to do that:内部服务错误抛出HttpServerErrorException如果您想处理它,您应该捕获此异常但是更好的方法是使用错误处理程序,您可以查看以下帖子以了解如何执行此操作:

  1. spring-rest-template-error-handling弹簧休息模板错误处理

  2. spring-boot-resttemplate-error-handling spring-boot-resttemplate-错误处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM