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.
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:
ResponseEntity<Success>
. It will not be responsible for returning error or exception responses.@ControllerAdvice
@ExceptionHandler
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.