0

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.

cantikia
  • 11
  • 4
  • Have you taken a look at the stack trace? Stack traces are pretty verboseabout the where (not necessarily the what). If this is not sufficient, the next step would be to use a debugger. – Turing85 Aug 12 '20 at 23:10
  • 1
    1) [There are no "best practices"](https://www.satisfice.com/blog/archives/5164). 2) There is a canonical Q&A about NPE's, what causes them, how to diagnose them and how to fix them: https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it – Stephen C Aug 12 '20 at 23:49
  • There is only one 'thing that causes NPE', and that is dereferencing a null pointer: and the stack trace tells you exactly where it happened. [Caveat: actually there is another thing, and that is `throw new NullPointerException();`, which is done occasionally on detecing null parameters, to simplify debugging later on.] – user207421 Aug 13 '20 at 00:28

0 Answers0