0

USER.GET() gives error and idk both why happens and how to google. Is there anyone who knows how to solve this error ?

thanks for your concern!!

@GetMapping("/users/{id}")
public EntityModel<User> retrieveUser(@PathVariable int id) {
    User user = service.findOne(id);
    if(user == null) {

        throw new UserNotFoundException("id-" + id);

    }


   //FOLLOWING LINE GIVES ERROR
    EntityModel<User> model = new EntityModel<>(user.get());
    WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());
    model.add(linkTo.withRel("all-users"));

}

1 Answers1

0

You are checking whether your returned Optional is null, but that is not enough, as Optional wraps either null or your object. Therefore you need to check wether your Optional actually contains a user object. In your case adjusting the code as follows should work, checking if the Optional is empty, instead of null.

@GetMapping("/users/{id}")
public EntityModel<User> retrieveUser(@PathVariable int id) {
    User user = service.findOne(id);
    if(user.isEmpty()) {

        throw new UserNotFoundException("id-" + id);

    }


   //FOLLOWING LINE GIVES ERROR
    EntityModel<User> model = new EntityModel<>(user.get());
    WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());
    model.add(linkTo.withRel("all-users"));

}

A good guide to Optionals in Java: https://www.baeldung.com/java-optional

Ali Nasserzadeh
  • 1,365
  • 7
  • 15