Explanation:
In the code snippet above, the BookController
class includes:
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.
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.