What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

Saveendra Ekanayake picture Saveendra Ekanayake · Jun 30, 2016 · Viewed 198k times · Source

I have written simple rest application using Spring MVC 4 (or Spring-Boot). Within the controller I have return ResponseEntity. But in some cases I want to give success JSON and if there is validation error I want to give error JSON. Currently success and error responses are totally different, So I have created 2 classes for error and success. Within the controller I want to return ResponseEntity<Success> , if the internal logic is okay. Otherwise I want to return ResponseEntity<Error>. Is there any way to do it.

Success and Error are the 2 classes that i use to represent success and error response.

Answer

Mark Norman picture Mark Norman · Apr 27, 2018

I recommend using Spring's @ControllerAdvice to handle errors. Read this guide for a good introduction, starting at the section named "Spring Boot Error Handling". For an in-depth discussion, there's an article in the Spring.io blog that was updated on April, 2018.

A brief summary on how this works:

  • Your controller method should only return ResponseEntity<Success>. It will not be responsible for returning error or exception responses.
  • You will implement a class that handles exceptions for all controllers. This class will be annotated with @ControllerAdvice
  • This controller advice class will contain methods annotated with @ExceptionHandler
  • Each exception handler method will be configured to handle one or more exception types. These methods are where you specify the response type for errors
  • For your example, you would declare (in the controller advice class) an exception handler method for the validation error. The return type would be ResponseEntity<Error>

With this approach, you only need to implement your controller exception handling in one place for all endpoints in your API. It also makes it easy for your API to have a uniform exception response structure across all endpoints. This simplifies exception handling for your clients.