Search code examples
javaspringhttpresttemplate

Spring ResponseErrorHandler without parsing objects


I am using SpringBoot with RestTemplate to communicate with another application. However, I am unable to change its API and this external service always Returns 200OK return code.

By Default, we have ResponseErrorHandler that reacts to all 4xx and 5xx response codes but in my case when there is an exception I get 200OK with one JSON field errors.

I have created a custom error handler and bundled it into my rest template by using:

restTemplate.errorHandler(new MyCustomErrorHandler());

I have also overrided hasError() method but inside I have to parse this object to check whether it contains fields with errors...

Is this a good approach for error handling? Should I parse response twice? I seek for the clean solution for such problems but I want to avoid parsing message twice every time I use external service


Solution

  • Error handler will only be invoked if an error state is returned, 200 is not an error state so it is not handled.

    You can change this behavior by overriding hasError method ResponseErrorHandler to check for error message or any indication for error.

    public class MyCustomErrorHandler implements ResponseErrorHandler {
    
    @Override
    public boolean hasError(ClientHttpResponse httpResponse) 
            throws IOException {
    
        //TODO check your criteria for error
    }