How to recover object by URI by passing parameter and showing Request Status

Asked

Viewed 20 times

0

I’m learning to work with Spring REST, I can already recover object by URL in Postman, but in my URL if I pass a parameter e.g.: http://localhost:8080/categories/50 It shows as status 200 OK if you found it or not, but I wanted it to show 404 otherwise it will be foundif, I came to see some examples but the example I took did not work.

*my Code


@RequestMapping("/categorias")
public class CategoriaResource {


@Autowired 
    private CategoriasRepository categoriasRepository;


@GetMapping("/{codigo}")
public Optional<Categoria> buscarPeloCodigo(@PathVariable Long codigo) {
    
    
     return categoriasRepository.findById(codigo);
}

Exemplo que encontrei na internet; Não consigo utilizar o metodo findOne, ele pede para o retorno do meu método seja, Optional

@GetMapping("/{codigo}")
public ResponseEntity<Categoria> buscarPeloCodigo(@PathVariable Long codigo) {
     Categoria categoria = categoriaRepository.findOne(codigo);
     return categoria != null ? ResponseEntity.ok(categoria) : ResponseEntity.notFound().build();
}

2 answers

0

Dayson, see if this format helps you:

if (categoria == null) {
    return new ResponseEntity(HttpStatus.NOT_FOUND);
}
return new ResponseEntity(categoria, headers, HttpStatus.OK);

0

Ideal is to place this logic within a service, for example:

if(categoria == null){
  trown new NotFoundError("Categoria não encontrada)
}
//exemplo de classe NotFound
public class NotFoundError extends Exception {
    
    public NotFoundError(String message) {
        super(message);
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.