Bird
0
0

In a Spring Boot REST controller, how can you return a 404 Not Found status along with a JSON error message in the response body?

hard📝 Application Q8 of 15
Spring Boot - Request and Response Handling
In a Spring Boot REST controller, how can you return a 404 Not Found status along with a JSON error message in the response body?
AUse @ResponseStatus(HttpStatus.NOT_FOUND) on the controller method without a response body
BThrow new RuntimeException("Resource not found") and rely on default error handling
CReturn new ResponseEntity<>("Resource not found", 404)
DReturn ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "Resource not found"))
Step-by-Step Solution
Solution:
  1. Step 1: Use ResponseEntity with status

    ResponseEntity allows setting both status and body explicitly.
  2. Step 2: Set status to NOT_FOUND

    Use HttpStatus.NOT_FOUND enum for clarity and correctness.
  3. Step 3: Provide a JSON body

    Returning a Map or object will serialize to JSON with the error message.
  4. Final Answer:

    Return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "Resource not found")) -> Option D
  5. Quick Check:

    ResponseEntity with status and body returns custom status and message [OK]
Quick Trick: Use ResponseEntity.status() with body for custom status and message [OK]
Common Mistakes:
  • Using raw integer 404 instead of HttpStatus enum
  • Throwing exceptions without custom handlers for message
  • Using @ResponseStatus without response body

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes