0
RezerwacjaInfoDTO getRezerwacjaInfo(int rezerwacjaId) throws Exception {

    Integer osobaId = Math.abs(loginMgr.getLoggedUserInfo().getUserId());
    RezerwacjaInfoDTO rezInfo = rezMgr.getRezerwacjaInfo(rezerwacjaId);

    return Optional
            .ofNullable(rezInfo)
            .filter(rez -> rez.getOsobaId() == osobaId)
            .orElseThrow(() -> new Exception("Brak rezerwacji o podanym numerze"));
}

When I call it:

getRezerwacjaInfo(81504)

I got Exception, but rezInfo.getOsobaId() == 81504 (i see it in debugger)

when I remove this line:

.filter(rez -> rez.getOsobaId() == osobaId)

function returns object RezerwacjaInfoDTO.

What is rong with this line??

Olek
  • 319
  • 8
  • 24

1 Answers1

1

If your variable rezInfo is null then your optional throws exception also rezInfo.getOsobaId() == osobaId is true then exception occurs.

When you remove the filter it does not throws exception because your rezInfo is not null.

May be another alternative is to handle optional in caller method.

Optional<RezerwacjaInfoDTO> getRezerwacjaInfo(int rezerwacjaId) {

    Integer osobaId = Math.abs(loginMgr.getLoggedUserInfo().getUserId());
    RezerwacjaInfoDTO rezInfo = rezMgr.getRezerwacjaInfo(rezerwacjaId);

    return Optional
            .ofNullable(rezInfo);
}

void callerMethod() throws Exception {
    getRezerwacjaInfo(...)
            .filter(rez -> rez.getOsobaId() == osobaId)
            .orElseThrow(() -> new Exception("Brak rezerwacji o podanym numerze"));
}
Emre Savcı
  • 3,034
  • 2
  • 16
  • 25
  • Thanks for explenation. It was stupid mistake, should be rez.getOsobaId().equals(osobaId) – Olek Aug 23 '18 at 09:52
  • @Olek just declare `osobaId` as `int` and `==` will work as intended (and it will even improve the performance). – Holger Aug 23 '18 at 10:12