Handling Exceptions in RESTful User Responses

public class BookController {

    private BookService bookService;

    // Method to retrieve a book by its 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
    public ResponseEntity<String> handleBookNotFoundException(BookNotFoundException ex) {
        // Log the exception details for debugging

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

    // ... other methods or exception handlers ...


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.

Last updated

Need US based Java Developers

Visit Katyella

Katyella LLC http://katyella.com