# Global REST Error Responses via @ControllerAdvice

```java
@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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://book.katyella.com/springboot/recipes/global-rest-error-responses-via-controlleradvice.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
