Skip to content

Commit

Permalink
refactor: 커스텀 에러 valid 어노테이션 해결
Browse files Browse the repository at this point in the history
  • Loading branch information
sss4920 committed Jan 1, 2024
1 parent d142114 commit 83c4750
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
Expand Down Expand Up @@ -36,7 +37,8 @@ protected ResponseEntity<ApiResponse> handleCustomException(CustomException e) {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
protected ResponseEntity<ApiResponse> handleConstraintDefinitionException(final MethodArgumentNotValidException e) {
FieldError fieldError = e.getBindingResult().getFieldError();
return ResponseEntity.status(e.getStatusCode())
.body(ApiResponse.error(Error.BAD_REQUEST_VALIDATION, e.getMessage()));
.body(ApiResponse.error(Error.BAD_REQUEST_VALIDATION, fieldError.getDefaultMessage()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,22 @@ public void initialize(TitleValid constraintAnnotation) {

@Override
public boolean isValid(String title, ConstraintValidatorContext context) {
System.out.println("여기는 오는건가");
context.disableDefaultConstraintViolation();

if (title == null) {
context.buildConstraintViolationWithTemplate("제목에 null값이 들어옵니다.") //defaultMessage 생성
.addConstraintViolation();
return false;
}

// 커스텀 예외를 던집니다.
// null, 공백으로만 이뤄지는 경우, 빈 값인 경우 ''
if (title.isBlank()) {
context.buildConstraintViolationWithTemplate("제목이 공백으로만 차있습니다.")
context.buildConstraintViolationWithTemplate("제목이 공백으로만 차있습니다.") //defaultMessage 생성
.addConstraintViolation();
return false;
}
// 길이가 1보다 작거나 10보다 큰 경우
// 제목이 비어있는 경우
if (title.isEmpty()) {
context.buildConstraintViolationWithTemplate("제목이 비어있습니다. ")
.addConstraintViolation();
Expand Down

0 comments on commit 83c4750

Please sign in to comment.