Skip to content

Commit

Permalink
[fix] @Valid 예외 핸들러 추가 (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
soeunkk committed Aug 29, 2022
1 parent 5da7993 commit 24e325a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package com.nadoyagsa.pillaroid.common.controller;

import java.io.IOException;
import java.time.format.DateTimeParseException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.nadoyagsa.pillaroid.common.exception.InternalServerException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
Expand Down Expand Up @@ -54,4 +57,20 @@ protected ApiResponse methodArgumentTypeMismatchError(MethodArgumentTypeMismatch
log.error(ex.getMessage());
return ApiResponse.error(ErrorCode.BAD_PARAMETER_TYPE);
}

// 유효성 검사 실패 시
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = {MethodArgumentNotValidException.class})
protected ApiResponse methodArgumetNotValidException(MethodArgumentNotValidException ex) {
log.error(ex.getMessage());
return ApiResponse.error(ErrorCode.BAD_PARAMETER, ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
}

// JSON 직렬화, 역직렬화 실패 (ex. 타입 변환 실패)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = {JsonProcessingException.class})
protected ApiResponse jsonProcessingException(JsonProcessingException ex) {
log.error(ex.getMessage());
return ApiResponse.error(ErrorCode.BAD_PARAMETER);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,10 @@ public static <T> ApiResponse<T> success(T data) {
public static <T> ApiResponse<T> error(ErrorCode errorCode) {
return new ApiResponse<>(errorCode.getErrorIdx(), errorCode.getErrorStatus(), errorCode.getDetail(), null);
}

// 상세 오류 메시지를 포함
public static <T> ApiResponse<T> error(ErrorCode errorCode, String causeMessage) {
String message = String.format("%s(%s)", errorCode.getDetail(), causeMessage);
return new ApiResponse<>(errorCode.getErrorIdx(), errorCode.getErrorStatus(), message, null);
}
}
6 changes: 3 additions & 3 deletions src/main/java/com/nadoyagsa/pillaroid/dto/AlarmTimeDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@
@Getter
@Builder
public class AlarmTimeDto {
@NotNull
@NotNull(message = "morning 필수")
private LocalTime morning;
@NotNull
@NotNull(message = "lunch 필수")
private LocalTime lunch;
@NotNull
@NotNull(message = "dinner 필수")
private LocalTime dinner;

public AlarmTime toEntity(User user) {
Expand Down

0 comments on commit 24e325a

Please sign in to comment.