# Handling Exceptions in RESTful User Responses

```java
@RestController
@RequestMapping("/api/books")
public class BookController {

    @Autowired
    private BookService bookService;

    // Method to retrieve a book by its ID
    @GetMapping("/{id}")
    public ResponseEntity<Book> getBookById(@PathVariable Long id) {
        Book book = bookService.findBookById(id)
                .orElseThrow(() -> new BookNotFoundException("Book with ID: " + id + " not found."));
        return new ResponseEntity<>(book, HttpStatus.OK);
    }

    // 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 methods or exception handlers ...
}
```

**Explanation:**

In the code snippet above, the `BookController` class includes:

1. **Method `getBookById`:**
   * It uses the `bookService` to attempt to find the book. If the book is not found, `bookService.findBookById(id)` will return an empty `Optional`, and the `orElseThrow` method will throw a `BookNotFoundException`.
   * The exception message includes the ID of the book that was not found, providing clarity in the logs and to the API users.
2. **Exception Handler `handleBookNotFoundException`:**
   * This method remains the same as before. It handles the `BookNotFoundException` by logging the exception details and returning a user-friendly message along with a 404 Not Found status.

By including the `getBookById` method, we demonstrate a typical scenario in a RESTful service where a requested resource (in this case, a book) might not exist, leading to an exception that is gracefully handled by the `handleBookNotFoundException` method.

***

This structure ensures that your REST API for book management not only handles requests but also deals with exceptions in a user-friendly manner, improving the reliability and usability of your service.


---

# 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/handling-exceptions-in-restful-user-responses.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.
