Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot return 204 No-Content when List is empty [duplicate]

I have a controller that should return 204-No Content when no element exists in the list returned by the repository. In Spring when I return an empty list, the response status is 200-OK. I found a way to solve this setting my controller to return a Response Entity, but there is another way of doing this? I don't want to throw a exception, since a empty list in my use case makes sense, and can't use @ResponseStatus because in the use case the list can have elements too and so I need to return 200-OK and the list.

I solved using this approach, but I want to return a List<Parcela> in my controller and 204-No content

@GetMapping(path = "/contratos/{numeroContrato}/parcelas", params = "status")
ResponseEntity<List<Parcela>> filtrarParcelasPorStatus(@PathVariable String documento,
        @PathVariable String numeroContrato, @RequestParam StatusParcela status) {
    try {
        List<Parcela> parcelasFiltradas = veiculosUsecase.filtrarParcelasPorStatus(documento, numeroContrato,
                status);
        if (parcelasFiltradas.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<>(parcelasFiltradas, HttpStatus.OK);
    }
    catch (ParcelasNaoEncontradasException e) {
        throw new NotFoundException(
                "Nao e possivel listar as parcelas porque nao foi encontrado o contrato para o numero de contrato e cliente informado",
                "Nao e possivel listar as parcelas porque nao foi encontrado o contrato para o numero de contrato e cliente informado",
                HttpStatus.NOT_FOUND.toString(), "External - Veiculos API");
    }
}
like image 209
ghn1712 Avatar asked Feb 10 '26 13:02

ghn1712


2 Answers

Returning

return new ResponseEntity<>(HttpStatus.NO_CONTENT);

will return 204-No content. This is the right way to do it. Works for me just fine as well

like image 132
Michael Gantman Avatar answered Feb 13 '26 10:02

Michael Gantman


There are a few ways to return custom HTTP status code:

  1. Throw an exception and put an annotation on your custom exception

    @ResponseStatus(HttpStatus.NO_CONTENT)
    public class EmptyListException extends RuntimeException {}
    
  2. Be more organized and put the same thing into @ControllerAdvice

    @ControllerAdvice
    class GlobalControllerExceptionHandler {
        @ResponseStatus(HttpStatus.NO_CONTENT)
        @ExceptionHandler(EmptyListException.class)
        public void handleException() {}
    }
    
  3. Use your @ResponseEntity like you did.

    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    

Although it makes more sense to use exceptions for error codes (4XX and 5XX). I used ResponseEntity at first as well, but you can see yourself how messy your controller become.

It may be a matter of taste, but I would recommend creating your "business" exceptions like EmptyListException, throwing them in your service layer and then handling them in the separate @ControllerAdvice. That way it will be easier to read and support.

like image 39
ottercoder Avatar answered Feb 13 '26 08:02

ottercoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!