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) {
....
}
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With