Spring Boot @RestControllerAdvice Example

1. Introduction

@RestControllerAdvice is a Spring Boot annotation used for global error handling in RESTful services. It combines @ControllerAdvice and @ResponseBody annotations, meaning that data returned from methods annotated with @ExceptionHandler, @InitBinder, or @ModelAttribute in the advice will be rendered into the response body directly.

Key Points:

1. @RestControllerAdvice is typically used to define a global exception handler for REST APIs.

2. It allows you to apply exception handling to a range of controllers or specific packages.

3. Exception handler methods within a @RestControllerAdvice class do not need to be annotated with @ResponseBody.

2. Implementation Steps

1. Create a Spring Boot project with REST capabilities.

2. Define exception classes for different types of exceptions that may occur.

3. Create a @RestControllerAdvice class with @ExceptionHandler methods for the defined exceptions.

4. Run the application and simulate different exceptions to ensure global handling works as expected.

3. Implementation Example

Here is the complete code that demonstrates the usage of @RestControllerAdvice annotation:
// Step 2: Define custom exception classes
class ResourceNotFoundException extends RuntimeException {
    ResourceNotFoundException(String message) {
        super(message);
    }
}

class DataFormatException extends RuntimeException {
    DataFormatException(String message) {
        super(message);
    }
}

// Step 3: Create a @RestControllerAdvice class with exception handlers
@RestControllerAdvice
public class GlobalRestExceptionHandler {

    // Handle resource not found exceptions
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }

    // Handle data format exceptions
    @ExceptionHandler(DataFormatException.class)
    public ResponseEntity<String> handleDataFormatException(DataFormatException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
    }

    // Generic exception handler for other uncaught exceptions
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGeneralException(Exception ex) {
        return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

// Step 4: Main class to start the Spring Boot application
@SpringBootApplication
public class RestControllerAdviceExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(RestControllerAdviceExampleApplication.class, args);
    }
}

// Test the application by throwing these exceptions from a REST controller.

Output:

// If a ResourceNotFoundException is thrown:
Status: 404 NOT FOUND
Body: Resource not found message
// If a DataFormatException is thrown:
Status: 400 BAD REQUEST
Body: Data format error message
// If any other exception is thrown:
Status: 500 INTERNAL SERVER ERROR
Body: An error occurred: <generic error message>

Explanation:

1. ResourceNotFoundException and DataFormatException are custom exceptions used to illustrate specific error conditions in a REST API.

2. GlobalRestExceptionHandler is annotated with @RestControllerAdvice, indicating it provides global exception handling for REST controllers.

3. Each method within GlobalRestExceptionHandler is marked with @ExceptionHandler to handle different types of exceptions. Since it's a @RestControllerAdvice, there is no need to add @ResponseBody.

4. The handleResourceNotFound method provides a custom response for ResourceNotFoundException with a 404 status.

5. The handleDataFormatException method handles DataFormatException, returning a 400 status.

6. handleGeneralException is a catch-all that handles all other exceptions that don't have specific handlers, returning a 500 status.

7. RestControllerAdviceExampleApplication is the main class used to run the Spring Boot application, and it demonstrates how the application will handle exceptions globally.


Comments