Handle errors while using RestTemplate


Error Handling

  • While using RestTemplate we may get a different type of exceptions, we can handle all exceptions at the global level.
  • Create our own custom error handler which implements ResponseErrorHandler interface and need to provide an implementation for hasError() and handleError() methods.
  • hasError() will call for every HTTP response, we can check the condition here and return true or false.
  • Once hasError() returns true, handleError() will execute.
  • Set error handler to rest template at creation time.

Controller

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

	@Autowired
	private UserService userService;

	@GetMapping("/getUser/{userId}")
	@ResponseBody
	public Object getUser(@PathVariable("userId") int userId) {
		return userService.getUser(userId);
	}

}

Service

package com.example.demo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class UserService {

	private final RestTemplate restTemplate;

	public UserService(RestTemplateBuilder restTemplateBuilder) {
		this.restTemplate = restTemplateBuilder.errorHandler(new MyErrorHandler()).build();
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
		MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
		converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
		messageConverters.add(converter);
		this.restTemplate.setMessageConverters(messageConverters);
	}

	public Object getUser(int userId) {
		return this.restTemplate.getForObject("https://jsonplaceholder.typicode.com/todoss/" + userId, Object.class);
	}
}

Error handler

package com.example.demo;

import java.io.IOException;

import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

public class MyErrorHandler implements ResponseErrorHandler{

	@Override
	public boolean hasError(ClientHttpResponse response) throws IOException {
		return response.getStatusCode().is4xxClientError();
	}

	@Override
	public void handleError(ClientHttpResponse response) throws IOException {
		System.out.println(response.getBody());
	}

}