How to return a "not found" feature in Spring?

Asked

Viewed 894 times

2

I’m running some tests on Spring to return error 404 in case he doesn’t find one id when searching in Repository, but is giving 200 OK.

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<?> buscar(@PathVariable("id") Long id) {
    Optional<Livro> livro = livrosRepository.findById(id);

    if(livro == null) {
        return ResponseEntity.notFound().build();
    }

    return ResponseEntity.status(HttpStatus.OK).body(livro);
}`

Does anyone know what might be going on?

  • 2

    How about changing if para if(!livro.isPresent())? Your book attribute is an Optional, and most likely it is not null.

2 answers

6


I see two ways to do what you want:

1 - Same as @Tom Melo commented

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<?> buscar(@PathVariable("id") Long id) {
    Optional<Livro> livro = livrosRepository.findById(id);

    if(!livro.isPresent()) { // Mudança aqui
        return ResponseEntity.notFound().build();
    }

    return ResponseEntity.status(HttpStatus.OK).body(livro);
}

This way you use the Optional isPresent method

2 - Or otherwise

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<?> buscar(@PathVariable("id") Long id) {
    Livro livro = livrosRepository.findById(id).orElse(null);//Mudança aqui

    if(livro == null) {
        return ResponseEntity.notFound().build();
    }

    return ResponseEntity.status(HttpStatus.OK).body(livro);
}

This way you hope to return a Book and if you do not find it will be null, by your line of thought this seems more appropriate but the two methods will do the same thing in the end

  • It worked! That’s right the object is not null. Thank you all for the help!

  • 2

    Good, remember to accept the answer

3

Your code can become more declarative using the methods of Optional, without the need for a if:

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<?> buscar(@PathVariable("id") Long id){
    return livrosRepository.findById(id)
      .map(ResponseEntity::ok)
      .orElseGet(() -> ResponseEntity.notFound().build());
}

Browser other questions tagged

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