Sub topic 6
Quick mappings with @ResponseStatus and ResponseStatusException
This chapter assumes you can write a Spring Boot REST controller, know the common HTTP status codes, and know the difference between checked and unchecked exceptions. It covers the two lightest ways to turn an exception into a status code, and when to stop using them.
Two ways to set a status
Spring MVC gives you two built-in mappings that need no handler method:
@ResponseStatusis an annotation. You put it on an exception class, and every time that exception escapes a controller, Spring answers with that status.ResponseStatusExceptionis an exception you throw directly. It carries the status and an optional reason, so no dedicated class is needed.
Both are handled by ResponseStatusExceptionResolver, one of the resolvers Spring MVC tries when a controller throws.
@ResponseStatus on an exception class
Use it when the same failure always maps to the same status.
package com.example.orders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ProductNotFoundException extends RuntimeException {
public ProductNotFoundException(long id) {
super("Product " + id + " was not found");
}
}Any controller that throws ProductNotFoundException now returns 404. The annotation also accepts a reason attribute. Setting it makes Spring call response.sendError(...), which forwards the request to /error. The body then comes from Boot's default error handling, not from your code. Without reason, Spring only sets the status.
ResponseStatusException at the throw site
Use it for one-off cases where a new exception class would be clutter.
package com.example.orders;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
@RestController
class CustomerController {
private final Map<Long, String> customers = Map.of(1L, "Ada");
@GetMapping("/customers/{id}")
String get(@PathVariable long id) {
String name = customers.get(id);
if (name == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer " + id + " was not found");
}
return name;
}
}In Spring 6 and later, ResponseStatusException extends ErrorResponseException. With spring.mvc.problemdetails.enabled=true, the response body is a ProblemDetail, and the reason becomes its detail field.
Choosing between them
| Approach | Strength | Limit |
|---|---|---|
| `@ResponseStatus` on a class | One line, reusable | Status is fixed, no custom body fields |
| `ResponseStatusException` | No extra class | Status is repeated at each throw site |
| `@ExceptionHandler` | Full control of body and logging | More code |
Limits to know
@ResponseStatus couples your domain exception to HTTP. That is a problem if the exception lives in a service layer that should not know about web concerns. You also cannot add fields such as orderId to the body. Once you want either, move to an @ExceptionHandler, covered in the next chapters.
Exercise
A service class throws ProductNotFoundException, which you want to return 404. Why might annotating it with @ResponseStatus(HttpStatus.NOT_FOUND) be a poor choice, and what is the alternative?
Show answer
The annotation ties a service-layer exception to HTTP, and it cannot add fields such as the product id to the response body. Leave the exception free of web annotations and map it in an @ExceptionHandler method, ideally in a @RestControllerAdvice, where you can set the status and build a ProblemDetail.