Everyday Dev System

@ExceptionHandler 사용법 본문

내배캠 주요 학습/TIL : Today I Learned

@ExceptionHandler 사용법

chaeyoung- 2023. 7. 25. 22:19

참조 : https://github.com/thesun4sky/spring-blog/blob/lv4/

 

GitHub - thesun4sky/spring-blog

Contribute to thesun4sky/spring-blog development by creating an account on GitHub.

github.com

(LV4 브랜치에서 확인할 수 있다.)

 

 

 

 

아래는 Dto 클래스 코드이다.

package com.sparta.myblog.dto;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class UserRequestDto {
    // login and sing up Request DTO

    @Pattern(regexp = "^[a-z0-9]{4,10}$" , message = "username이 정규식에 맞지 않습니다.")
    @NotBlank
    private String username;


    @Pattern(regexp = "^[a-zA-Z0-9/[\\{\\}\\[\\]\\/?.,;:|\\)*~`!^\\-_+<>@\\#$%&\\\\\\=\\(\\'\\\"]/g]{8,15}$", message = "비밀번호가 정규식에 맞지 않습니다.")
    @NotBlank
    private String password;

    private boolean admin = false;

    // admin 확인 토큰
    private String adminToken;

}

 

 

 

아래 코드는 해당 코드가 입력되어 있는 클래스 내에서 

MethodArgumentNotValidException 해당 예외가 발생했을 경우에

해당 메서드를 실행한다는 의미이다.

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseEntity<RestApiResponseDto> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        RestApiResponseDto restApiException = new RestApiResponseDto(HttpStatus.BAD_REQUEST.value(),ex.getBindingResult().getAllErrors().get(0).getDefaultMessage(),null );
        return new ResponseEntity<>(
                // HTTP body
                restApiException,
                // HTTP status code
                HttpStatus.BAD_REQUEST
        );
    }

 

 

 

 

postman으로 요청을 보내보자.

 

 

 

 

디버깅을 하여 살펴보면 다음과 같다.

 

 

Dto 클래스 내에 Validation message를 볼 수 있다.

이를 클라이언트 측으로 전달해보자.

 

 

먼저, Add to Watches를 하여 어떻게 참조할 수 있는지를 가져오자.

상단에 위치된 코드의 edit을 하여 복사하여 가져온다.

 

ex.bindingResult).errors).get(2)).defaultMessage 이다.

ex.getBindingResult().getAllErrors().get(0).getDefaultMessage() 로 가져와서 메시지를 출력할 수 있다.

첫번째 ValidationFieldError의 defaultMessage만 가져온 것이다.

 

 

 

아래와 같이 클라이언트 측에 반환된다.

'내배캠 주요 학습 > TIL : Today I Learned' 카테고리의 다른 글

7월 마지막주 WIL  (0) 2023.07.30
wsl에서 안되면 power shell을 써라  (0) 2023.07.26
7월 25일 TIL  (0) 2023.07.25
Steam() 활용하기  (0) 2023.07.18
후발대 강의  (0) 2023.07.17