> For the complete documentation index, see [llms.txt](https://book.katyella.com/springboot/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://book.katyella.com/springboot/recipes/global-rest-error-responses-via-controlleradvice.md).

# 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
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
