Global REST Error Responses via @ControllerAdvice

@ControllerAdvice
public class GlobalExceptionHandler {

    // Global exception handler for BookNotFoundException
    @ExceptionHandler(BookNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity<String> handleBookNotFoundException(BookNotFoundException ex) {
        // Log the exception details for debugging
        Logger.log(ex.getMessage());

        // Return a user-friendly message and the appropriate HTTP status
        return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body("Book not found. Please check the provided book ID.");
    }

    // ... other global exception handlers ...
}

Explanation: In RESTful services, ensuring consistent and user-friendly error responses across the entire application is crucial. The @ControllerAdvice annotation in Spring Boot allows you to handle exceptions globally, avoiding the need to declare exception handlers in each controller. Just by having a class with this annotation in the class path. Here's how you can implement global exception handling for a book management RESTful service:


Code Implementation:

  1. Annotation @ControllerAdvice: This annotation declares the class as a global exception handler, making the exception handling methods within applicable across all controllers.

  2. Method handleBookNotFoundException:

    • This method is marked with @ExceptionHandler(BookNotFoundException.class), indicating it handles exceptions of type BookNotFoundException.

    • The @ResponseStatus(HttpStatus.NOT_FOUND) annotation ensures that a 404 Not Found status is returned.

    • The method logs the exception details and returns a ResponseEntity with a user-friendly error message.

Benefits of Using @ControllerAdvice:

  • Consistency: Ensures that the same exception across different controllers results in a consistent response.

  • Cleaner Code: Reduces duplication by avoiding repetitive exception handlers in each controller.

  • Centralized Configuration: Makes it easier to manage and maintain exception handling logic in one place.

By leveraging @ControllerAdvice or @RestControllerAdvice (for RESTful services where the response body is always expected), you can efficiently manage exceptions globally, ensuring that your RESTful service is robust, consistent, and user-friendly.


This approach to handling exceptions globally streamlines your error management strategy, making your RESTful service more maintainable and your error responses more predictable and informative.

Last updated

Need US based Java Developers

Visit Katyella

Katyella LLC http://katyella.com