Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- JPA주의사항
- Q 클래스
- 최종 프로젝트
- Filter
- 스프링 부트 기능
- JPA
- ERD 작성
- jpa에러
- JoinColumn
- REST란
- json
- Unsatisfied dependency
- @IdClass
- 스프링 부트 공식 문서
- 복합키
- 인텔리제이
- uncheck Exception
- 빈생성안됨
- git
- jpa회원가입
- spring서버
- REST API 규칙
- github
- 스프링부트오류
- 1차캐시
- Spring Spring boot 차이
- json gson 차이
- Error creating bean with name
- jwt메서드
- queryDSL
Archives
- Today
- Total
Everyday Dev System
@ExceptionHandler 사용법 본문
참조 : 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 |