Video in progress

Strong Junior 🌱 Spring

What are the ways to return an HTTP status code from a controller?

There are three: set the status yourself with ResponseEntity, put @ResponseStatus on the method or the exception class, or throw an exception and set the status in an @ExceptionHandler.

📖 Answer

If the status depends on the situation — ResponseEntity:

return found ? ResponseEntity.ok(dto) : ResponseEntity.notFound().build();

If the status is always the same — @ResponseStatus on the method:

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public OrderDto create(@RequestBody NewOrder o) { ... }

Or via an exception:

@ResponseStatus(HttpStatus.NOT_FOUND)
public class OrderNotFound extends RuntimeException { ... }

or throw new ResponseStatusException(HttpStatus.CONFLICT, "Buyurtma allaqachon to'langan");

What people usually do in practice: a successful response is a plain object or @ResponseStatus(CREATED), errors are domain exceptions, and @RestControllerAdvice turns them into statuses. The service layer knows nothing about HTTP, and controllers stay clean.