Discover how to stop your app from crashing when data is missing and keep users happy!
Why Handling not found exceptions in Spring Boot? - Purpose & Use Cases
Imagine building a web app where users request data by ID, and you manually check if the data exists every time before responding.
If the data is missing, you have to write extra code to handle that case and send a proper error message.
Manually checking for missing data everywhere leads to repeated code and mistakes.
You might forget to handle the missing case, causing confusing errors or crashes.
This makes your app unreliable and hard to maintain.
Handling not found exceptions lets you centralize the missing data logic.
Spring Boot can automatically catch when data is missing and send a clear error response.
This keeps your code clean and your app stable.
if (data == null) { return ResponseEntity.status(404).body("Not found"); }
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {}You can build apps that gracefully handle missing data without cluttering your main logic.
When a user requests a product that doesn't exist, your app automatically returns a friendly 404 error page instead of crashing.
Manual checks for missing data are repetitive and error-prone.
Exception handling centralizes missing data responses.
Spring Boot makes it easy to send clear 404 errors automatically.
Practice
Solution
Step 1: Understand the role of not found exceptions
Not found exceptions indicate that a requested resource does not exist on the server.Step 2: Identify the correct response behavior
Returning a 404 HTTP status code clearly informs the client that the resource is missing.Final Answer:
To return a clear 404 status when a requested resource is missing -> Option DQuick Check:
Not found exceptions = 404 status [OK]
- Confusing not found with server errors
- Thinking it improves database speed
- Assuming it retries requests automatically
Solution
Step 1: Recall Spring Boot annotations for HTTP status
The @ResponseStatus annotation sets the HTTP status code for exceptions or controller methods.Step 2: Match the annotation to 404 status
Using @ResponseStatus(HttpStatus.NOT_FOUND) on a custom exception class sends 404 automatically.Final Answer:
@ResponseStatus(HttpStatus.NOT_FOUND) -> Option AQuick Check:
@ResponseStatus + NOT_FOUND = 404 [OK]
- Using @ExceptionHandler instead of @ResponseStatus
- Assuming @NotFoundException is a valid annotation
- Using incorrect annotation names
@GetMapping("/items/{id}")
public Item getItem(@PathVariable Long id) {
return itemRepository.findById(id)
.orElseThrow(() -> new ItemNotFoundException(id));
}What happens if the item with the given id does not exist?
Solution
Step 1: Analyze the use of orElseThrow
If the item is not found, orElseThrow triggers the custom ItemNotFoundException.Step 2: Understand exception handling with @ResponseStatus
If ItemNotFoundException is annotated with @ResponseStatus(HttpStatus.NOT_FOUND), Spring returns 404 status.Final Answer:
An ItemNotFoundException is thrown and HTTP 404 status is returned -> Option BQuick Check:
orElseThrow + @ResponseStatus = 404 error [OK]
- Assuming null is returned instead of exception
- Confusing 404 with 500 server error
- Thinking empty object is returned
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ProductNotFoundException extends RuntimeException {
public ProductNotFoundException(Long id) {
super("Product " + id + " not found");
}
}
@GetMapping("/products/{id}")
public Product getProduct(@PathVariable Long id) {
return productRepo.findById(id).orElseThrow(() -> new ProductNotFoundException(id));
}What is the likely problem if the client always receives HTTP 500 instead of 404 when a product is missing?
Solution
Step 1: Verify annotation presence
The exception class is correctly annotated with @ResponseStatus(HttpStatus.NOT_FOUND).Step 2: Understand Spring's exception mapping
If Spring returns 500, it means it does not recognize the exception mapping to 404, possibly due to package scanning or configuration issues.Final Answer:
The exception is thrown but Spring does not map it to 404 -> Option AQuick Check:
Annotated exception but 500 means mapping failed [OK]
- Assuming missing no-arg constructor causes 500
- Thinking @ResponseStatus is missing when it is present
- Believing explicit handler is always required
ResourceNotFoundException occurs. Which approach correctly achieves this?Solution
Step 1: Understand global exception handling
Using @ControllerAdvice with @ExceptionHandler allows centralized handling of exceptions across controllers.Step 2: Return ResponseEntity with 404 and JSON body
The handler method can build a ResponseEntity with HttpStatus.NOT_FOUND and a JSON error message for clients.Final Answer:
Create a class annotated with @ControllerAdvice and a method with @ExceptionHandler(ResourceNotFoundException.class) returning ResponseEntity with status 404 and error body -> Option CQuick Check:
Global handler + ResponseEntity = custom 404 JSON [OK]
- Relying only on @ResponseStatus without custom JSON body
- Annotating exception class as controller
- Manually throwing exceptions in every method
Ready to prove it?
Pass the test and this pattern moves unknown
