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.
A ResponseEntity is returned. We give ResponseEntity a custom status code, headers, and a body. With @ResponseBody , only the body is returned. The headers and status code are provided by Spring.
ResponseEntity represents the whole HTTP response: status code, headers, and body. As a result, we can use it to fully configure the HTTP response. If we want to use it, we have to return it from the endpoint; Spring takes care of the rest.
ResponseEntity<> is a generic class with a type parameter, you can specify what type of object to be serialized into the response body. @ResponseBody is an annotation, indicates that the return value of a method will be serialized into the body of the HTTP response.
Yes, Service returning domain object should be preferable to a Service returning ResponseEntity<> . There is no best practices. Having said that, you should think of implementing something like Hexagonal or Layered architecture.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With