๐Ÿ’ Spring

Optional ๊ฐ’์ด ์žˆ์„ ๋•Œ Exception ์ฒ˜๋ฆฌ

iseunghan 2022. 6. 29. 14:50
๋ฐ˜์‘ํ˜•

ํšŒ์› ๋„๋ฉ”์ธ์—์„œ Username์ด ์ค‘๋ณต์ด ๋˜๋ฉด ์•ˆ๋˜๋ฏ€๋กœ ์•„๋ž˜ ๊ฐ™์ด ๋กœ์ง์„ ์ถ”๊ฐ€ํ–ˆ์Šต๋‹ˆ๋‹ค.

Optional<Account> account = accountRepository.findByUsername(username);

if (account.isPresent()) throw new AccountDuplicateException(username);

ํ•˜์ง€๋งŒ Optional์„ ๋ฐ˜ํ™˜ํ•˜์ง€ ๋ง๊ณ  ifPresent๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ฐ”๋กœ Exception์„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

accountRepository.findByUsername(username)
    .ifPresent(a -> {
    	throw new AccountDuplicateException(username)
    });

ํ›จ์”ฌ ๋” ๊ฐ„๊ฒฐํ•ด์ง€๊ณ  ์•Œ์•„๋ณด๊ธฐ ์‰ฌ์šด ์ฝ”๋“œ๊ฐ€ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.

๋ฐ˜์‘ํ˜•