简体   繁体   中英

Handling of various exception cases in rest template call

I am making rest template call to get the data from other microservice for this I am using the exchange method. This I am doing when a particular function gets called and below is the sample code for the same.

    @Service   
 public void findUserById() 
 {
    String username = "chathuranga";
    String password = "123";
    Integer userId = 1;

    String url = "http://localhost:8080/users/" + userId;

    //setting up the HTTP Basic Authentication header value
    String authorizationHeader = "Basic " + DatatypeConverter.printBase64Binary((username + ":" + password).getBytes());

    HttpHeaders requestHeaders = new HttpHeaders();
    //set up HTTP Basic Authentication Header
    requestHeaders.add("Authorization", authorizationHeader);
    requestHeaders.add("Accept", MediaType.APPLICATION_JSON_VALUE);

    //request entity is created with request headers
    HttpEntity<AddUserRequest> requestEntity = new HttpEntity<>(requestHeaders);

    ResponseEntity<FindUserResponse> responseEntity = restTemplate.exchange(
            url,
            HttpMethod.GET,
            requestEntity,
            FindUserResponse.class
    );

//    if (responseEntity.getStatusCode() == HttpStatus.OK) {
  //      System.out.println("response received");
        System.out.println(responseEntity.getBody());
    //} else {
    //    System.out.println("error occurred");
     //   System.out.println(responseEntity.getStatusCode());
    //}
}

To handle the various exceptions code for example 500, 404 I want to made resttemplate builder class, (not the commented code) Which must be coded in different class for this I am referring this (custom hadler part)

I am not using try catch as it is not good approach when multiple calls happen in production environment. I am also getting resource access exception while using exchange function which also needs to handle. Now I am not getting how this class of custom handler should be called for handling response like 500. If someone can help me with the sample code that would be very helpfull as I cannot test my code because it is not deployed for testing purpose till now

here is a sample

@ControllerAdvice
public class ErrorHandler {

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(ResourceAccessException.class)
    public @ResponseBody
    String handleResourceAccessException(
            ResourceAccessException ex) {
        return "internal server error";
    }
}

When you use @ControllerAdvice, it will catch the exception you mention in @ExceptionHandler and here you can handle it the way you want.

If you don't want to return the response to the client right away, (for example, ignore ResourceAccessException and continue), you can override the handleError method of DefaultResponseErrorHandler, which is used by RestTemplate to handle the non 2xx codes.

public class ErrorHandler extends DefaultResponseErrorHandler {

@Override
  public void handleError(ClientHttpResponse response, HttpStatus statusCode) {
      // write your code here
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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