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");
}
}