Quick revision
The short answer
There are two styles. We can return ResponseEntity and choose the status explicitly: ResponseEntity.notFound().build() for 404, ResponseEntity.noContent().build() for 204 and ResponseEntity.status(HttpStatus.CONFLICT).body(...) for 409. Or we can throw an exception and map it to a status with @ExceptionHandler in a @RestControllerAdvice, with @ResponseStatus on the exception class, or with ResponseStatusException from anywhere. Both work; the important thing is to pick one approach and use it consistently across the API.
What to remember
In this answer, we saw two families of options for 404, 204 and 409. ResponseEntity builders, notFound().build(), noContent().build() and status(HttpStatus.CONFLICT), decide the status in the controller. Exceptions mapped with @ExceptionHandler in a @RestControllerAdvice, @ResponseStatus on an exception class, or ResponseStatusException let the status follow from what went wrong. A good default is success codes in the controller and errors as domain exceptions mapped centrally to problem details, used the same way across the whole API.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
There are two styles. We can return ResponseEntity and choose the status explicitly: ResponseEntity.notFound().build() for 404, ResponseEntity.noContent().build() for 204 and ResponseEntity.status(HttpStatus.CONFLICT).body(...) for 409. Or we can throw an exception and map it to a status with @ExceptionHandler in a @RestControllerAdvice, with @ResponseStatus on the exception class, or with ResponseStatusException from anywhere. Both work; the important thing is to pick one approach and use it consistently across the API.
Why this question is asked
Status codes are part of an API's contract, and clients write code against them: a 404 means show 'not found', a 409 means ask the user to pick another name. Getting them right is easy for one endpoint and hard across fifty if every developer chooses a different technique. Interviewers ask for the code options to see whether we know the tools and can explain when each fits. In this answer, we will recap the three status codes, write each case with ResponseEntity, then with exceptions in three flavours, and finish with how to choose one consistent approach.
1A Quick Recap of 404, 204 and 409
404 Not Found means the resource the URL names does not exist, for example GET /orders/999 when there is no order 999. 204 No Content means the request succeeded and there is deliberately no body, which suits a successful DELETE. 409 Conflict means the request could not be completed because it conflicts with the current state of the resource, such as creating a customer with an email that already exists, or updating a record someone else changed in the meantime.
By default, a Spring MVC handler that returns normally gets 200 and one that throws an unhandled exception gets 500. To send anything else, we either return the status ourselves or let Spring translate an exception into it.
2Option 1: ResponseEntity in the Controller
ResponseEntity holds a status, headers and an optional body, and has builder methods for the common statuses. The controller decides the status directly.
Notice the trade-off. Everything is visible in the method, which is easy to read. But the return type of create became ResponseEntity<?>, because it returns either a problem detail or an order, and the existence check happens in the controller, where it races with another request creating the same reference. The not-found decision also has to be repeated in every method that looks up an order.
3Option 2: Throw an Exception and Map It in an Advice
The second style lets the service express what went wrong with a domain exception, and one @RestControllerAdvice translates exceptions to statuses for every controller.
6 messages in order. Play them, or step through them one at a time.
Notice that the service can now detect the duplicate in the right place: by catching the DataIntegrityViolationException from a unique constraint on the reference column and throwing DuplicateOrder, which is safe even when two requests race. Notice also @ResponseStatus on the delete method: a void method with it returns that status with no body, which is a neat way to write 204.
4Option 3: @ResponseStatus on the Exception, or ResponseStatusException
Two lighter variants exist. We can annotate the exception class itself, so Spring uses that status whenever it is thrown and not handled elsewhere. Or we can throw ResponseStatusException, a built-in exception that carries a status, from any code that runs during the request.
| Approach | Where the status is decided | Good for |
|---|---|---|
ResponseEntity builders | In each controller method | Simple APIs, unusual responses |
@ExceptionHandler in an advice | One central class | Consistent errors across the API |
@ResponseStatus on exception | On the exception class | Small apps, quick mapping |
ResponseStatusException | Wherever it is thrown | Controllers and prototypes |
@ResponseStatus on method | On the handler method | Fixed success codes like 204 |
@ResponseStatus on exceptions is quick, but it ties a domain exception to HTTP, which is awkward if the same service is called from a message listener. ResponseStatusException is handy in controllers and prototypes, but throwing it from a service mixes HTTP into business code. Both still produce a problem detail body when spring.mvc.problemdetails.enabled=true, because Spring's ErrorResponse support covers them; check your version for the exact default body.
5Choosing One Consistent Approach
Any of these works, but mixing them is what hurts. If one controller returns an empty 404, another throws a ResponseStatusException with a message, and a third has a handler that returns a custom JSON shape, clients see three different error bodies for the same situation.
For most APIs I would choose this combination: success statuses chosen in the controller with ResponseEntity.created(...) or @ResponseStatus(NO_CONTENT), and every error expressed as a domain exception mapped to a problem detail in one @RestControllerAdvice, typically extending ResponseEntityExceptionHandler so Spring's own exceptions such as validation errors get the same format. The service stays free of HTTP types, every error body looks the same, and a new error type needs one handler method.
6Follow-up questions
Should DELETE of a missing resource return 404 or 204?
Both are defensible. DELETE is idempotent, so some APIs return 204 even when the resource is already gone, which makes retries harmless. Others return 404 to tell the client it named something that does not exist. Pick one, document it, and apply it everywhere.
Why use ProblemDetail instead of a custom error class?
ProblemDetail implements RFC 9457, a standard JSON error format with type, title, status, detail and instance, plus custom properties. Clients and tools already understand it, and Spring produces it for its own exceptions, so our errors and the framework's look the same.
7Conclusion
In this answer, we saw two families of options for 404, 204 and 409. ResponseEntity builders, notFound().build(), noContent().build() and status(HttpStatus.CONFLICT), decide the status in the controller. Exceptions mapped with @ExceptionHandler in a @RestControllerAdvice, @ResponseStatus on an exception class, or ResponseStatusException let the status follow from what went wrong. A good default is success codes in the controller and errors as domain exceptions mapped centrally to problem details, used the same way across the whole API.
Open with
There are two main styles. The explicit one is ResponseEntity in the controller: ResponseEntity.notFound().build() for a missing order, often from an Optional with map(ResponseEntity::ok).orElseGet, ResponseEntity.noContent().build() after a delete, and ResponseEntity.status(HttpStatus.CONFLICT) with a problem detail body for a duplicate.
Then, if they want more
It's very readable, but the decisions repeat in every method and the return types get loose. The other style is exceptions. The service throws domain exceptions like OrderNotFound or DuplicateOrder, and a @RestControllerAdvice with @ExceptionHandler methods maps them to 404 and 409 as RFC 9457 problem details.
That keeps HTTP out of the service, and the duplicate can be detected properly from the unique constraint, which is safe under concurrency. There are lighter variants too: @ResponseStatus on the exception class, or throwing ResponseStatusException with a status from anywhere, which is handy in controllers but mixes HTTP into business code if used in services.
For 204 I like @ResponseStatus(HttpStatus.NO_CONTENT) on a void delete method. What matters most is consistency, so my default would be success codes in the controller and all errors as domain exceptions mapped centrally to problem details, so every endpoint returns the same error shape.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Spring Web MVC
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Return 404 when an order is not found, 204 after a delete, and 409 when a duplicate is...": https://scrivio-interview-library.netlify.app/spring-boot/rest-controllers/52a1116c81/