0

I can't get my RestTemplate to throw all the exceptions it encounter on its way down the controller's endpoint. To make my thought more clear, I'll provide an example.

Simple endpoint PATCH /api/entity/{entity_id} which requires a body in form of JSON. Let's suppose that the entity that is being patched (of {entity_id} id) is not changed after client's call because the provided JSON body is the same as the actual, persisted entity.

In that case, in my service class, I throw an ObjectsAreEqualException with 200 OK HTTP code and some message:

public EntityResponse update(Long entityId, EntityUpdateRequest updateRequest) {
    Entity toUpdate = entityRepository.findById(entityId).get();
    // some constraint checks
    if(anythingToUpdate(entityToUpdate, updateRequest)) {
        throw new ObjectsAreEqualException();
    }
    // more constraint checks

    // logic and return
}

My main question is: how to tell RestTemplate to perceive each thrown (by me) exception as actual exception / (error)? Not only the 4xx and 5xx exceptions, but also the ones of other codes, for instance 200 OK.

For interested, my thoughts and solutions that did not work are below.

===

If ObjectsAreEqualException would be to have a 4xx or 5xx status codes, then I've got no problem. However, I'm stubborn and want to stay with 200 OK.

I know that the DefaultResponseErrorHandler that RestTemplate uses has a method hasError which returns true, when the exception's status code is 4xx or 5xx.

I map errors to ApiError (custom) class (which is same as Spring's default error JSON), thus I thought to maybe use ObjectMapper on response body and if mapping were to be successful, then that'd mean there was an exception thrown.

However, I can't use getResponseBody(ClientHttpResponse) in hasError (but I can perfectly use it in handleError, which is a mystery to me right now) as it throws stream closed exception.

IceMajor
  • 37
  • 5

0 Answers0