Spring Boot : Validation 예외 Advice로 관리하기

김아무개·2023년 10월 17일
0

Spring Boot 🍃

목록 보기
77/95

1. 예외 응답 객체 생성

- Valid 예외 출력 객체

ValidExceptionResponse.java

@Getter @Builder
public class ValidExceptionResponse {
	private String field;
    private String message;
}

- 예외 응답 객체

ExceptionResponse.java

@Getter @Builder
public class ExceptionResponse <t> {
    private LocalDateTime timestamp;
    private String message;
    private t details;
}

2. Advice 클래스 작성

MyExceptionHandler.java

@RestControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                  HttpHeaders headers,
                                                                  HttpStatus status,
                                                                  WebRequest request) {
        List<ValidExceptionResponse> list = new ArrayList<>();

        ex.getBindingResult()
                .getAllErrors()
                .forEach(objectError -> {
                    FieldError field = (FieldError) objectError;
                    String message = objectError.getDefaultMessage();

                    list.add(ValidExceptionResponse.builder()
                            .field(field.getField())
                            .message(message)
                            .build());
                });


        return new ResponseEntity<>(ExceptionResponse.<List<ValidExceptionResponse>>builder()
                                                .timestamp(LocalDateTime.now())
                                                .message("valid error")
                                                .details(list)
                                                .build(),
                                    HttpStatus.BAD_REQUEST);
    }

}

추상 클래스 ResponseEntityExceptionHandler 를 상속받으면 Spring MVC 앱에서 발생하는 예외를 처리할 수 있다.

> https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.html


3. Valid 적용 할 데이터 객체 생성

User.java

@Data
@AllArgsConstructor
public class User {
    private Integer id;

    @Size(min = 2, message = "2글자 이상 입력해주세요.")
    private String name;

    @Past
    private LocalDateTime joinDate;
}

4. Controller 작성

@RestController
@RequiredArgsConstructor
@RequestMapping("/users")
public class UserController {

    @PostMapping
    public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
        User saved = service.save(user);
        
        URI location = ServletUriComponentsBuilder
                .fromCurrentRequest()
                .path("/{id}")
                .buildAndExpand(saved.getId())
                .toUri();

        return ResponseEntity.created(location).build(); 
    }
}

5. 실행!

profile
Hello velog! 

0개의 댓글