Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

비지니스 검증을 할 때 도메인과 서비스 어느 쪽에서 예외를 터뜨려야 할까? #3

Open
Yiseull opened this issue Nov 14, 2023 · 1 comment

Comments

@Yiseull
Copy link
Owner

Yiseull commented Nov 14, 2023

상황 설명

투표 참여 기능을 개발 중인데, 예외 처리에 대한 고민이 생겼다. 기능의 규칙은 다음과 같다.
사용자는 오직 진행 중인 투표에만 참여할 수 있어야 한다. 사용자가 이미 종료된 투표에 참여하려고 시도한다면, 이때 예외를 발생시켜야 한다. 이런 상황에서, 예외 발생은 도메인과 서비스 중 어느 곳에서 처리해야 하는 것이 적절할까?

예시는 실제 로직보다 간소화했습니다.

1. 도메인에서 예외 발생

Vote

public void validateVoting() {
	final LocalDateTime now = LocalDateTime.now();
	if (this.endTime.isAfter(now)) {
		throw new BusinessException(ErrorCode.VOTE_CANNOT_PARTICIPATE);
	}
}

VoteService

public void participateVote(
	final Long voteId,
	final Long itemId,
	final Long memberId,
) {
	final Vote vote = voteReader.read(voteId);

	vote.validateVoting();

	voteManager.participate(vote, memberId, itemId);
}

2. 서비스에서 예외 발생

Vote

public boolean isVoting() {
	final LocalDateTime now = LocalDateTime.now();
	return this.endTime.isAfter(now);
}

VoteService

public void participateVote(
	final Long voteId,
	final Long itemId,
	final Long memberId,
) {
	final Vote vote = voteReader.read(voteId);

	if (!vote.isVoting()) {
		throw new BusinessException(ErrorCode.VOTE_CANNOT_PARTICIPATE);
	}

	voteManager.participate(vote, memberId, itemId);
}
@Yiseull
Copy link
Owner Author

Yiseull commented Feb 17, 2024

투표 도메인에서 예외를 발생시키는 방법도 물론 고려해봤지만, 결국 서비스에서 예외를 발생시키는 방향으로 결정을 내렸다. 그 이유는 다음과 같다.

"투표가 종료되었을 때 예외를 발생시키는 것"을 특정 비즈니스 로직 중 하나로 보았다. 우리 프로젝트에서 서비스는 비즈니스 명세를 담당하는 UseCase 역할을 수행하고 있다. 따라서 이런 비즈니스 로직은 서비스 레이어에서 처리해야 한다고 판단했다.

물론, 이 결정이 정답인지는 확신할 수 없다. 그러나 현재의 상황에서는 서비스 레이어에서 예외를 처리하는 것이 가장 적절하다고 판단했다. 이런 결정은 프로젝트의 요구 사항이나 개발자의 선호도 등 많은 요인에 의해 달라질 수 있다.

그래서 가장 중요한 것은 내가 선택한 방식이 프로젝트에 가장 적합한지, 그리고 모든 팀원들이 이해하고 지원할 수 있는지 확인하는 것이다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant