caliari77 :
Using @ResponseStatus allows setting the status of a Rest response in Spring. But how could this be used for different kinds of status that could come from the same request?
For example, there is a method in the controller that may return a 200 or a 404. How could I define these statuses just using @ResponseStatus in one method?
BeUndead :
Typically you wouldn't do this with @ResponseStatus
. Instead, you can use ResponseEntity<...>
as the return type of your method. If the 'type' of returned item can change, ResponseEntity<?>
or ResponseEntity<Object>
works too.
For example:
@GetMapping("/{key}")
public ResponseEntity<Thing> getThing(final @PathVariable String key) {
final Thing theThing = this.thingService.get(key);
final ResponseEntity<?> response;
if (theThing.someProperty()) {
response = ResponseEntity.ok(theThing);
} else {
response = ResponseEntity.status(HttpStatus.NOT_MODIFIED).body(null);
}
return response;
}