javaspringspring-bootresterror-handling

What is the best way to return different types of ResponseEntity in Spring-Boot (Error Handling for REST with Spring)


I have written simple REST application in Spring Boot (Spring Framework).

It returns ResponseEntity<Success> as Success response in the controller level. But I want to return a completely different Error response ResponseEntity<Error>, if there is an error (validation error, logic error, runtime error) in the API.

Success & Error responses are completely different for the application. Success & Error are the 2 java classes which the application uses to represent Success & Error responses.

What is the best way to return different types of ResponseEntity in Spring-Boot (Best way to handle the errors for REST with Spring)?


Solution

  • 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:

    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.