Search code examples
javaspringhateoas

Spring HATEOAS error handling with VndErrors


I am struggling to find a clean way of handling errors produced by an HATEOAS enabled api.

Basically our backend service is a spring application that in case of exceptions uses @ControllerAdvice to return a VndErrors instance back to the consumer.

VndErrors is provided by spring-hateoas and once returned will be serialised and marked as application/vnd.error.

On the service consumer part we are also using spring-hateoas and we communicate with the backend service via a standard RestTemplate.

The default ResponseErrorHandler in the RestTemplate throws exceptions for client, server or uknown http statues responses but it doesn't attempt to deserialise the response body in anyway.

public MyBusinessConcept myBusinessConcept() {
    try {
        return restTemplate().exchange("http://foo/bar",  ..., MyBusinessConcept.class).getBody();
    } catch (HttpClientErrorException e) {
        // ???
    }
}

How can we get back the VndErrors instance from a failed http response?


Solution

  • After lot of researches I happen to find an answer within some other spring module.

    Basically a solution is to implement the ResponseErrorHandler interface, either using inheritance or composition (better) to fallback to the DefaultResponseErrorHandler. The implementation would use a ResponseExtractor<VndErrors> to deserialise our errors back.