Bird
0
0

Consider this code snippet:

medium📝 Debug Q14 of 15
Spring Boot - Exception Handling
Consider this code snippet:
 @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?
AThe exception is thrown but Spring does not map it to 404
BThe exception is not annotated with @ResponseStatus
CThe controller method does not handle the exception explicitly
DThe exception class is missing a no-argument constructor
Step-by-Step Solution
Solution:
  1. Step 1: Verify annotation presence

    The exception class is correctly annotated with @ResponseStatus(HttpStatus.NOT_FOUND).
  2. 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.
  3. Final Answer:

    The exception is thrown but Spring does not map it to 404 -> Option A
  4. Quick Check:

    Annotated exception but 500 means mapping failed [OK]
Quick Trick: 500 instead of 404 means Spring missed exception mapping [OK]
Common Mistakes:
  • Assuming missing no-arg constructor causes 500
  • Thinking @ResponseStatus is missing when it is present
  • Believing explicit handler is always required

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes