Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle null return value in spring boot

I have a question about spring boot. When I want to get the specific user from my database everything is ok but how can I handle the null response (There is no such a user)? I want to handle the return value of null as ResponseEntity but when there is a user with that id I need to return User details. So I could not set return value as ResponseEntity. Here is the screenshot of the problem:

enter image description here

Here is the code:

@GetMapping("get/{id}")
public User findById(@PathVariable int id) throws Exception {
    try {
        if(userMapper.findById(id) != null) {
            return userMapper.findById(id);
        }else {
            throw new Exception("YOK ULAN YOK");
        }
    }catch (Exception e) {
        // TODO: Make perfect
        return new User(-1);
    }
}

and here is the return value:

{
"email": null,
"username": null,
"password": null,
"name": null,
"surname": null,
"age": 0,
"photoLink": null,
"dateOfBirth": null,
"phoneNumber": null,
"city": null,
"country": null,
"friendList": null,
"plan": null,
"id": -1,
"planned": false

}

I don't want to send a -1 user, I want to send a user not found response. How can I handle it?

Thanks,

like image 334
DGulyasar Avatar asked Oct 29 '25 21:10

DGulyasar


1 Answers

the best way is to change method return type from User to ResponseEntity<?>, smth. like:

@GetMapping("get/{id}")
public ResponseEntity<?> findById(@PathVariable int id) throws Exception {
    User user = userMapper.findById(id);
    if (user == null) {
       return ResponseEntity.notFound().build();
    }
    return ResponseEntity.ok(user);
}

or using optional:

@GetMapping("get/{id}")
public ResponseEntity<?> findById(@PathVariable int id) throws Exception {
    return Optional.ofNullable(userMapper.findById(id))
       .map(ResponseEntity::ok)
       .orElseGet(ResponseEntity.notFound()::build);
}
like image 124
Andrey B. Panfilov Avatar answered Nov 01 '25 10:11

Andrey B. Panfilov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!