Skip to content

Commit

Permalink
기타 예외사항 구현 (#37)
Browse files Browse the repository at this point in the history
* feat: 방 생성 예외사항 추가

* feat: 방 참가 예외사항 추가

* test: 방 생성 조건 test 추가

* test: 방 참가 실패 테스트 추가

* feat: 게임 시작 조건 검증 구현

* feat: 체팅 전송시 내용이 누락되면 안된다

* feat: 플레이어별 기술 사용시 예외 점검
  • Loading branch information
waterricecake committed Oct 14, 2024
1 parent 9ea176b commit be00c4e
Show file tree
Hide file tree
Showing 18 changed files with 345 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@

public record ErrorResponse(
LocalDateTime localDateTime,
Integer errorCode,
String message,
List<FieldErrorResponse> errorList
) {
static ErrorResponse create(final String message) {
return new ErrorResponse(LocalDateTime.now(), message, new ArrayList<>());
static ErrorResponse create(final Integer errorCode, final String message) {
return new ErrorResponse(LocalDateTime.now(), errorCode, message, new ArrayList<>());
}

static ErrorResponse create(final String message, List<FieldErrorResponse> errorList) {
return new ErrorResponse(LocalDateTime.now(), message, errorList);
static ErrorResponse create(final Integer errorCode, final String message, List<FieldErrorResponse> errorList) {
return new ErrorResponse(LocalDateTime.now(), errorCode, message, errorList);
}

public record FieldErrorResponse(String field, String value, String message) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
@Getter
@RequiredArgsConstructor
public enum ExceptionCode {
UNEXPECTED_EXCEPTION(000, "예상치 못한 예외입니다."),

INVALID_REQUEST(100, "잘못된 요청입니다."),
INVALID_ROOM_INFORMATION(101, "방 구성이 잘 못 되었습니다."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
protected ResponseEntity<ErrorResponse> Exception(Exception e) {
final ErrorResponse errorResponse = ErrorResponse.create(
ExceptionCode.UNEXPECTED_EXCEPTION.getCode(),
"예기치 않은 예외가 발생 했습니다."
);

Expand All @@ -42,6 +43,7 @@ protected ResponseEntity<ErrorResponse> BindException(BindException e) {
}

final ErrorResponse errorResponse = ErrorResponse.create(
ExceptionCode.INVALID_REQUEST.getCode(),
"",
errors
);
Expand All @@ -50,9 +52,10 @@ protected ResponseEntity<ErrorResponse> BindException(BindException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
}

@ExceptionHandler({RoomException.class, CitizenException.class, AuthException.class})
protected ResponseEntity<ErrorResponse> GlobalException(RuntimeException e) {
@ExceptionHandler(GlobalException.class)
protected ResponseEntity<ErrorResponse> GlobalException(GlobalException e) {
final ErrorResponse errorResponse = ErrorResponse.create(
e.getCodes(),
e.getMessage()
);

Expand All @@ -65,6 +68,7 @@ protected ResponseEntity<Object> HttpRequestMethodNotSupportedException(
final HttpRequestMethodNotSupportedException e
) {
final ErrorResponse errorResponse = ErrorResponse.create(
ExceptionCode.MISSING_AUTHENTICATION_HEADER.getCode(),
"HTTP 메서드를 확인해 주세요"
);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
Expand All @@ -75,6 +79,7 @@ protected ResponseEntity<Object> handleMissingServletRequestParameter(
final MissingServletRequestParameterException e
) {
final ErrorResponse errorResponse = ErrorResponse.create(
ExceptionCode.INVALID_CONTENT.getCode(),
"요청 파라미터를 확인해 주세요"
);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package mafia.mafiatogether.controller;

import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import mafia.mafiatogether.service.ChatService;
Expand Down Expand Up @@ -30,7 +31,7 @@ public ResponseEntity<List<ChatResponse>> findAllChat(@PlayerInfo PlayerInfoDto
@PostMapping
public ResponseEntity<Void> saveChat(
@PlayerInfo PlayerInfoDto playerInfoDto,
@RequestBody ChatRequest request
@Valid @RequestBody ChatRequest request
) {
chatService.saveChat(playerInfoDto.code(), playerInfoDto.name(), request);
return ResponseEntity.status(HttpStatus.CREATED).build();
Expand Down
24 changes: 20 additions & 4 deletions src/main/java/mafia/mafiatogether/domain/Room.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import mafia.mafiatogether.config.exception.CitizenException;
import mafia.mafiatogether.config.exception.ExceptionCode;
import mafia.mafiatogether.config.exception.RoomException;
import mafia.mafiatogether.domain.job.Job;
Expand Down Expand Up @@ -51,7 +52,14 @@ public void modifyStatus(final StatusType statusType, final Clock clock) {
this.status = status.getNextStatus(this, clock);
}

public void joinPlayer(final Player player) {
public void joinPlayer(final String name) {
if (players.containsKey(name)) {
throw new RoomException(ExceptionCode.INVALID_NAMES);
}
if (players.size() >= roomInfo.getTotal()) {
throw new RoomException(ExceptionCode.ROOM_FULL);
}
final Player player = Player.create(name);
if (master.equals(Player.NONE)) {
master = player;
}
Expand All @@ -75,8 +83,12 @@ public Player getPlayer(final String name) {
return players.get(name);
}

public String executeSkill(final String name, final Player target) {
final Player player = players.get(name);
public String executeSkill(final String name, final String targetName) {
final Player player = getPlayer(name);
final Player target = getPlayer(targetName);
if (!target.isAlive()) {
throw new CitizenException(ExceptionCode.NOT_ALIVE_PLAYER);
}
return player.getJob().applySkill(target, jobTarget);
}

Expand Down Expand Up @@ -122,7 +134,11 @@ public Boolean isMaster(final Player player) {
return this.master.equals(player);
}

public Integer getTotalPlayers(){
public Integer getTotalPlayers() {
return roomInfo.getTotal();
}

public boolean validateStartStatus() {
return roomInfo.getTotal() == players.size();
}
}
13 changes: 11 additions & 2 deletions src/main/java/mafia/mafiatogether/domain/RoomInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
import java.util.Queue;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import mafia.mafiatogether.config.exception.ExceptionCode;
import mafia.mafiatogether.config.exception.RoomException;
import mafia.mafiatogether.domain.job.Doctor;
import mafia.mafiatogether.domain.job.Job;
import mafia.mafiatogether.domain.job.Mafia;
import mafia.mafiatogether.domain.job.Police;
import mafia.mafiatogether.domain.job.Job;

@Getter
@RequiredArgsConstructor
Expand All @@ -21,6 +23,13 @@ public class RoomInfo {
private final int doctor;
private final int police;

public static RoomInfo of(final int total, final int mafia, final int doctor, final int police) {
if (total / 2 < mafia || total < 3 || mafia == 0) {
throw new RoomException(ExceptionCode.INVALID_ROOM_INFORMATION);
}
return new RoomInfo(total, mafia, doctor, police);
}

public Queue<Job> getRandomJobQueue() {
final List<Job> jobList = new ArrayList<>();
addTimes(new Mafia(), mafia, jobList);
Expand All @@ -30,7 +39,7 @@ public Queue<Job> getRandomJobQueue() {
return new LinkedList<>(jobList);
}

private void addTimes(final Job job, int times, final List<Job> jobList){
private void addTimes(final Job job, int times, final List<Job> jobList) {
for (int i = 0; i < times; i++) {
jobList.add(job);
}
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/mafia/mafiatogether/domain/job/JobTarget.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ public void addTarget(final JobType jobType, final Player player) {
}

public Player getTarget(final JobType jobType) {
if (!targets.containsKey(jobType)){
return Player.NONE;
}
return targets.get(jobType);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import java.sql.Timestamp;
import java.time.Clock;
import java.time.LocalDateTime;
import mafia.mafiatogether.config.exception.ExceptionCode;
import mafia.mafiatogether.config.exception.RoomException;
import mafia.mafiatogether.domain.Room;

public class WaitStatus extends Status {
Expand All @@ -21,6 +23,9 @@ public static WaitStatus create(final Clock clock) {

@Override
public Status getNextStatus(final Room room, final Clock clock) {
if (!room.validateStartStatus()) {
throw new RoomException(ExceptionCode.NOT_ENOUGH_PLAYER);
}
room.distributeRole();
return DayStatus.create(room.getPlayerCount(), clock);
}
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/mafia/mafiatogether/service/PlayerService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
import mafia.mafiatogether.domain.Player;
import mafia.mafiatogether.domain.Room;
import mafia.mafiatogether.domain.RoomManager;
import mafia.mafiatogether.service.dto.JobResponse;
import mafia.mafiatogether.service.dto.MafiaTargetResponse;
import mafia.mafiatogether.service.dto.PlayerExecuteAbilityRequest;
import mafia.mafiatogether.service.dto.PlayerExecuteAbilityResponse;
import mafia.mafiatogether.service.dto.JobResponse;
import org.springframework.stereotype.Service;

@Service
Expand All @@ -28,9 +28,8 @@ public PlayerExecuteAbilityResponse executeSkill(
final PlayerExecuteAbilityRequest request
) {
final Room room = roomManager.findByCode(code);
final Player target = room.getPlayer(request.target());
final Player player = room.getPlayer(name);
final String result = room.executeSkill(name, target);
final String result = room.executeSkill(name, request.target());

return new PlayerExecuteAbilityResponse(player.getJobSymbol().name(), result);
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/mafia/mafiatogether/service/RoomService.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public RoomCodeResponse create(final RoomCreateRequest request) {

public void join(final String code, final String name) {
final Room room = roomManager.findByCode(code);
room.joinPlayer(Player.create(name));
room.joinPlayer(name);
}

public RoomStatusResponse findStatus(final String code) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package mafia.mafiatogether.service.dto;

import jakarta.validation.constraints.NotNull;

public record ChatRequest(
@NotNull
String contents
) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ public record RoomCreateRequest(
) {

public RoomInfo toDomain() {
return new RoomInfo(total, mafia, doctor, police);
return RoomInfo.of(total, mafia, doctor, police);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import mafia.mafiatogether.domain.Message;
import mafia.mafiatogether.domain.Player;
Expand Down Expand Up @@ -53,8 +54,8 @@ void setRoom() {
room = roomManager.findByCode(code);
player1 = Player.create("power");
player2 = Player.create("metthew");
room.joinPlayer(player1);
room.joinPlayer(player2);
room.joinPlayer(player1.getName());
room.joinPlayer(player2.getName());
}

@Test
Expand Down Expand Up @@ -109,7 +110,8 @@ void setRoom() {
void 채팅_전송에_실패한다(
final String testCase,
final String code,
final String name
final String name,
final Optional<String> contents
) {
// given
final String basic = Base64.getEncoder().encodeToString((code + ":" + name).getBytes());
Expand All @@ -118,16 +120,17 @@ void setRoom() {
RestAssured.given().log().all()
.contentType(ContentType.JSON)
.header("Authorization", "Basic " + basic)
.body(Map.of("contents", "contents"))
.body(Map.of("contents", contents))
.when().post("/chat")
.then().log().all()
.statusCode(HttpStatus.BAD_REQUEST.value());
}

static Stream<Arguments> failCaseProvider() {
return Stream.of(
Arguments.of("방에 존재하지 않는 유저의 경우", code, "dali"),
Arguments.of("존재하지 않는 방의 경우", "testCode", "metthew")
Arguments.of("방에 존재하지 않는 유저의 경우", code, "dali", Optional.of("contents")),
Arguments.of("존재하지 않는 방의 경우", "testCode", "metthew", Optional.of("contents")),
Arguments.of("문자열이 비어있는 경우", code, "metthew", Optional.empty())
);
}
}
Loading

0 comments on commit be00c4e

Please sign in to comment.