I want to create a controller that passed a parameter search
as an input to findDuelIdOrEmail
method:
@RequestMapping(value = "/app/friend_search", method = RequestMethod.GET)
public ResponseEntity<List<FriendResponse>> getAll(
@RequestHeader("Authorization") String authToken,
@RequestParam(value = "search", required = false) Object search) throws Exception {
TokenPayload tokenPayload = tokenProvider.verifyAndDecode(authToken);
List<FriendResponse> friendResponseList = new ArrayList<>();
boolean isNull = search == null;
boolean isEmpty = search != null && search.toString().equals("");
if (isNull || isEmpty) return ResponseEntity.ok(friendResponseList);
friendResponseList.add(this.friendService.findByDuelIdOrEmail(search));
return ResponseEntity.ok(friendResponseList);
}
I have a findDuelIdOrEmail
method which contains a variable profile
that initialized with null
value. The code is shown below:
public FriendResponse findByDuelIdOrEmail(Object duelIdOrEmail) throws Exception {
Profile profile = null;
final String duelIdOrEmailString = duelIdOrEmail.toString();
final User userEmail = this.userRepository.findByEmail(duelIdOrEmailString);
if (userEmail == null) {
final int userId = this.generateUserId(new Long(duelIdOrEmailString));
profile = this.profileRepository.findByUserId(userId);
} else {
profile = this.profileRepository.findByUserId(userEmail.getId());
}
if (profile == null) {
throw new ResourceNotFoundException();
} else {
FriendResponse response = this.generateFriendResponse(profile, 1, null);
checkResponse(response);
return response;
}
My guess is the profile
variable caused NPE. I tried to handle the null
value by validating it with if(profile == null)
. But, I still got the NullPointerException
.
What is the best practice to handle this problem? Any tips will be appreciated.