Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return not found status from spring controller

I have following spring controller code and want to return not found status if user is not found in database, how to do it?

@Controller
public class UserController {
  @RequestMapping(value = "/user?${id}", method = RequestMethod.GET)
  public @ResponseBody User getUser(@PathVariable Long id) {
    ....
  }
}
like image 793
Sergey Avatar asked Mar 20 '14 14:03

Sergey


1 Answers

JDK8 approach:

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public ResponseEntity<User> getUser(@PathVariable Long id) {
    return Optional
            .ofNullable( userRepository.findOne(id) )
            .map( user -> ResponseEntity.ok().body(user) )          //200 OK
            .orElseGet( () -> ResponseEntity.notFound().build() );  //404 Not found
}
like image 77
wypieprz Avatar answered Oct 24 '22 08:10

wypieprz