Sub topic 6
Quick mappings with @ResponseStatus and ResponseStatusException
This chapter assumes you can write a Spring MVC controller, know the common HTTP status codes, and have read the earlier chapters on Spring Boot's default /error handling and custom exceptions. It covers the two lightest ways to turn an exception into a status code. They need no handler class, and each has limits that show up in real projects.
The two mechanisms
Both mechanisms are handled by the same component, ResponseStatusExceptionResolver. They differ in where you declare the status.
@ResponseStatusis an annotation. You put it on an exception class, so every throw of that class produces the same status.ResponseStatusExceptionis an exception you construct at the throw site. The status and reason are chosen at runtime, so one call site can pick any status.
Use @ResponseStatus when an exception always means the same thing. Use ResponseStatusException when the status depends on context, or when you don't want a new exception class.
@ResponseStatus on an exception class
Annotate a domain exception with the status it should produce:
package com.example.accounts;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.CONFLICT)
public class DuplicateEmailException extends RuntimeException {
public DuplicateEmailException(String email) {
super("Email " + email + " is already registered");
}
}A controller can then throw it without knowing anything about HTTP:
package com.example.accounts;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/accounts")
class AccountController {
private final Set<String> emails = ConcurrentHashMap.newKeySet();
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Map<String, String> register(@RequestParam String email) {
if (!emails.add(email)) {
throw new DuplicateEmailException(email);
}
return Map.of("email", email);
}
}The first request with a given email returns 201. A repeat returns 409.
The annotation has two attributes. code (aliased as value) is the status. reason is an optional message. The same annotation also works on controller methods, as @ResponseStatus(HttpStatus.CREATED) does above. There it sets the status for a normal return, which is useful for 201 and 204.
What the response body contains
reason changes how the response is written. Without it, the resolver sets the status and the response continues normally. With it, the resolver calls HttpServletResponse.sendError(status, reason). The servlet container then dispatches to /error, and Spring Boot's BasicErrorController writes the body.
Two things follow from this:
- The body is the default error JSON (
timestamp,status,error,path), not something you control. - The exception message does not appear unless you set
server.error.include-message. Its default isnever, so a client sees409 Conflictwith no explanation.
During development you can set server.error.include-message=always. In production, keep the default and return messages through a handler, as later chapters show.
Recent Spring Framework releases mark reason as deprecated. Check the Javadoc for your version before relying on it.
ResponseStatusException at the throw site
ResponseStatusException is an unchecked exception you build with a status and an optional reason. This is the controller from the plan:
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;
}
}You can also pass a cause. The cause never reaches the client, but it stays attached for logging:
package com.example.reports;
import java.time.YearMonth;
import java.time.format.DateTimeParseException;
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 ReportController {
@GetMapping("/reports/{month}")
String report(@PathVariable String month) {
try {
return "Report for " + YearMonth.parse(month);
} catch (DateTimeParseException e) {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, "Month must look like 2026-12", e);
}
}
}The exception exposes getStatusCode() and getReason(). In Spring Framework 6 it also implements ErrorResponse, so it can be rendered as a ProblemDetail. That matters once you add a global handler.
Where these mechanisms sit in the resolver chain
Spring MVC tries exception resolvers in a fixed order. The first one that handles the exception wins.
@ExceptionHandler methods are tried first. This ordering explains the most common failure with these two mechanisms.
Comparison
| Concern | @ResponseStatus on a class | ResponseStatusException |
|---|---|---|
| Where the status is set | Compile time, on the class | Runtime, at each throw site |
| Dynamic status or message | No | Yes |
| Needs a new exception class | Yes | No |
| Works on third-party exceptions | No, you can't edit them | Yes, wrap them |
| HTTP knowledge in the exception | Annotation only | In the throwing code |
| Can attach a cause | Normal exception chaining | Constructor argument |
Common errors
A catch-all handler overrides both
ExceptionHandlerExceptionResolver runs before ResponseStatusExceptionResolver. Suppose a @RestControllerAdvice declares @ExceptionHandler(Exception.class) as a safety net and does not extend ResponseEntityExceptionHandler. That handler matches every exception, including ResponseStatusException and annotated exceptions. Your 404 quietly becomes a 500.
The handler class in the plan avoids this by extending ResponseEntityExceptionHandler. That base class has a handler for ErrorResponseException, the parent of ResponseStatusException in Spring 6, and Spring picks the closest match. If you write your own catch-all, add either that base class or an explicit handler for ResponseStatusException.
The reason is missing from the body
With reason set, the body comes from /error, and the message is hidden by default. Setting server.error.include-message=always fixes it, but it affects every error response in the application, including ones you didn't intend to expose. A handler that returns a ProblemDetail gives you control per exception.
Annotating a framework or library exception
You can't add @ResponseStatus to a class you don't own. Catch it and rethrow a ResponseStatusException with the original as the cause, or write an @ExceptionHandler for it.
Using HTTP status codes in the domain layer
An exception such as DuplicateEmailException is meant to be thrown by service code. If a ResponseStatusException is thrown from a service, the service now depends on web classes. It also can't be reused from a batch job or message listener. A good rule is to throw ResponseStatusException only in controllers. Services throw domain exceptions, and the web layer maps them to statuses.
Expecting a body in MockMvc tests
sendError relies on the servlet container's error dispatch to /error. MockMvc does not perform that dispatch. A test that reads the body of a sendError response finds it empty. You can assert on the status, and on getErrorMessage() of the response if needed. To assert on JSON, produce the body in a handler, as the later chapters on ProblemDetail and testing show.
Choosing between them
Use these criteria:
- Pick
@ResponseStatuson a class when the exception always maps to one status and you want controllers free of HTTP details. - Pick
ResponseStatusExceptionwhen the status or message varies, when you only need it once, or when you are wrapping a library exception. - Pick a
@RestControllerAdvicehandler when the response body must follow a contract, when you need to log in one place, or when you must control which details reach the client.
The two mechanisms in this chapter set the status code well. They do not give you control over the body, and the chapters that follow add that control.
Exercise
A @RestControllerAdvice declares @ExceptionHandler(Exception.class) and returns a 500 ProblemDetail. It does not extend ResponseEntityExceptionHandler. A controller throws new ResponseStatusException(HttpStatus.NOT_FOUND, "missing"). What status does the client receive, and why? Name two ways to fix it.
Show answer
The client receives 500. ExceptionHandlerExceptionResolver runs before ResponseStatusExceptionResolver, and the catch-all handler matches every exception, so the ResponseStatusException never reaches the resolver that would honor its 404 status. Fixes: extend ResponseEntityExceptionHandler, which handles ErrorResponseException (the parent of ResponseStatusException in Spring 6) and is the closer match, or add an explicit @ExceptionHandler(ResponseStatusException.class) method that returns the exception's own status.
Exercise
You annotate OutOfStockException with @ResponseStatus(value = HttpStatus.CONFLICT, reason = "Out of stock"). A client calls the endpoint and gets a 409 with the default JSON body but no "Out of stock" text. Why, and how do you make the text appear per request?
Show answer
With reason set, the resolver calls sendError, and Spring Boot's BasicErrorController writes the body. The message is hidden because server.error.include-message defaults to never. Setting it to always shows it for every error, which can expose details. A better fix is an @ExceptionHandler in a @RestControllerAdvice that returns a ProblemDetail containing the text.