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:

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