rest webservices exception handling with spring boot

Viewed 730

I'm developing a REST client library and a REST server using spring/spring-boot. The library will be used as a dependency in other applications.

What is a best way to handle errors, I thought about handling the error on the server side using for example ControllerAdvice to map errors to an error DTO class. On the client side (which uses RestTemplate) I would like to:

  1. case of error (response 4xx/5xx), then deserialize error DTO and throw checked exception (which needs to be handled in the applications which use the library)
  2. in normal case just deserialize the expected DTO object and return.

I was trying to achieve that with ResponseErrorHandler and I came up with two solutions which don't totally satisfy me, so I would like to hear an opinion about them or get some better suggestions:

idea 1:

    public List<SomeDTO> list() throws MyException {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
    HttpEntity<String> request = new HttpEntity<>(headers);
    ResponseEntity<String> response = restTemplate.exchange("endpoint/getAll", HttpMethod.GET, request, String.class);
    String responseBody = response.getBody();
    try {
        if (MyResponseErrorHandler.isError(response.getStatusCode())) {
            ErrorInfo error = objectMapper.readValue(responseBody, ErrorInfo.class);
            throw new MyException();
        } else {
            List<SomeDTO> SomeDTOs = Arrays.asList(objectMapper.readValue(responseBody));
            return SomeDTOs;
        }
    } catch (IOException e) {
        throw new MyException();
    }
}

But it looks like a lot of boilerplate for each method.

idea 2 A

throw custom exception in ResponseErrorHandler, which needs to be Runtime or IOException, but in case of IOException is wrapped with ResourceAccessException. In the client method exception could be caught and another one rethrown. But somewhere (in catch block?) the error response needs to be mapped to custom exception (what also can throw IOException)

idea 2 B don't use ResponseErrorHandler, catch HttpClientErrorException, get response body from it in the catch block using getResponseBodyAsString, map it to custom error type (catching IOException))

Any thoughts? thanks in advance

1 Answers
Related