Home > database >  How to handle null return value in spring boot
How to handle null return value in spring boot

Time:08-20

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,

CodePudding user response:

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);
}

CodePudding user response:

We can try to define a exception with reponse status.

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
}

And then, in your controller, throw this exception

throw new ResourceNotFoundException()

Or, just set the status of Response directly.
BTW, a better approach is to define our business code to implement it.

  • Related