0
0
Spring Bootframework~30 mins

Handling not found exceptions in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling not found exceptions in Spring Boot
📖 Scenario: You are building a simple Spring Boot REST API for managing books in a library. Users can request details of a book by its ID.Sometimes, the requested book ID does not exist in the system. You want to handle this case gracefully by sending a clear error message and a proper HTTP status code.
🎯 Goal: Build a Spring Boot REST controller that returns book details by ID. If the book is not found, return a 404 Not Found response with a custom error message.
📋 What You'll Learn
Create a simple data structure to hold book information
Add a configuration variable for the error message
Implement a method to find a book by ID and throw a custom exception if not found
Create an exception handler to return a 404 status and error message
💡 Why This Matters
🌍 Real World
Handling not found exceptions is common in web APIs to inform clients clearly when requested data does not exist.
💼 Career
Backend developers often implement exception handling in Spring Boot to improve API reliability and user experience.
Progress0 / 4 steps
1
Create the initial book data structure
Create a Map<Integer, String> called books with these exact entries: 1 mapped to "Spring Boot Basics", 2 mapped to "Java Fundamentals", and 3 mapped to "REST API Design".
Spring Boot
Need a hint?

Use Map.of() to create an immutable map with the given entries.

2
Add a custom error message variable
Create a String variable called notFoundMessage and set it to "Book not found".
Spring Boot
Need a hint?

Just create a simple String variable with the exact name and value.

3
Implement method to find book or throw exception
Write a method called getBookById that takes an int id parameter and returns a String. Inside, use books.get(id) to get the book title. If the result is null, throw a new BookNotFoundException with notFoundMessage. Otherwise, return the book title.
Spring Boot
Need a hint?

Check if the book is null and throw the exception with the message variable.

4
Create exception handler for BookNotFoundException
Add a method annotated with @ExceptionHandler(BookNotFoundException.class) that returns a ResponseEntity<String>. The method should take a BookNotFoundException ex parameter and return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage()).
Spring Boot
Need a hint?

Use @ExceptionHandler annotation and return a ResponseEntity with 404 status and the exception message.