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