[그림일기 서비스 보고 공부하기] BusinessException을 RuntimeException에서 확장시키는 이유

오젼·2024년 8월 29일
0

https://mangkyu.tistory.com/205

RuntimeException은 unchecked exception!

checked exception의 경우 예외처리가 되지 않으면 컴파일 시점에서 잡힌다. 컴파일러가 확인하기 때문에 checked exception.
unchecked exception의 경우 런타임 시점에서 잡힌다. 컴파일러가 확인 안 하기 때문에 unchecked exception.

checked exception은 try-catch나 throws를 명시적으로 사용해야 한다.

저기서 말하는 불필요한 throws 전파는 불필요하게 throws를 전파되어야 할 상위 레이어마다 적어줘야 한다는 뜻인 것 같다.

+) ❗️unchecked exception의 경우 @Transactional과 같이 사용했을 때 예외 발생시 트랜잭션이 자동으로 롤백된다.

https://sup2is.github.io/2021/03/04/java-exceptions-and-spring-transactional.html

@Service
public class TransferService {
    @Autowired
    private AccountRepository accountRepository;

    @Transactional
    public void transfer(String fromAccountId, String toAccountId, BigDecimal amount) {
        Account fromAccount = accountRepository.findById(fromAccountId)
            .orElseThrow(() -> new AccountNotFoundException("출금 계좌를 찾을 수 없습니다."));
        Account toAccount = accountRepository.findById(toAccountId)
            .orElseThrow(() -> new AccountNotFoundException("입금 계좌를 찾을 수 없습니다."));

        if (fromAccount.getBalance().compareTo(amount) < 0) {
            throw new InsufficientFundsException("잔액이 부족합니다.");
        }

        fromAccount.withdraw(amount);
        toAccount.deposit(amount);

        accountRepository.save(fromAccount);
        accountRepository.save(toAccount);
    }
}

@Service
public class TransferService {
    @Autowired
    private AccountRepository accountRepository;

    @Transactional
    public void transfer(String fromAccountId, String toAccountId, BigDecimal amount) throws TransferException {
        try {
            Account fromAccount = accountRepository.findById(fromAccountId)
                .orElseThrow(() -> new AccountNotFoundException("출금 계좌를 찾을 수 없습니다."));
            Account toAccount = accountRepository.findById(toAccountId)
                .orElseThrow(() -> new AccountNotFoundException("입금 계좌를 찾을 수 없습니다."));

            if (fromAccount.getBalance().compareTo(amount) < 0) {
                throw new InsufficientFundsException("잔액이 부족합니다.");
            }

            fromAccount.withdraw(amount);
            toAccount.deposit(amount);

            accountRepository.save(fromAccount);
            accountRepository.save(toAccount);
        } catch (Exception e) {
            throw new TransferException("이체 중 오류가 발생했습니다.", e);
        }
    }
}

0개의 댓글