Skip to content

Commit

Permalink
240226 @Valid Nested Dto 검증
Browse files Browse the repository at this point in the history
  • Loading branch information
suzieep committed Feb 26, 2024
1 parent 08a2067 commit ad5eaa1
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
49 changes: 49 additions & 0 deletions TIL/240221.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# 240221 Custom Exception Handling (@(Rest)ControllerAdvice, @ExceptionHandler)

```json
{
"timestamp": "2024-02-21T00:45:12.820+00:00",
"status": 400,
"error": "Bad Request",
"trace": "org.springframework.web.bind.MethodArgumentNotValidException:
...
"message": "Validation failed for object='memberDto'. Error count: 1",
"errors": [
{
"codes": [
"NotEmpty.memberDto.name",
"NotEmpty.name",
"NotEmpty.java.lang.String",
"NotEmpty"
],
"arguments": [
{
"codes": [
"memberDto.name",
"name"
],
"defaultMessage": "name",
"code": "name"
}
],
"defaultMessage": "name is required",
"objectName": "memberDto",
"field": "name",
"bindingFailure": false,
"code": "NotEmpty"
}
],
"path": "/member"
}
```
=> 이렇게 원하는 리턴 모양을 만들어서 내려주자
```java
@ControllerAdvice
public class CustomExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<String> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("name is required");
}
}
```
37 changes: 37 additions & 0 deletions TIL/240226.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# 240226 @Valid Nested Dto 검증

## 겪은 문제
- @Valid 어노테이션을 사용하는데, Nested Dto에 대한 validation이 안됐다!!


## 해결 방법 예시 코드

```java
class MemberController {
@PostMapping("/member")
public ResponseEntity<MemberDto> createMember(@Valid @RequestBody MemberDto memberDto) {
return ResponseEntity.ok(memberService.createMember(memberDto));
}
}
```

```java
class MemberDto {
@NotEmpty(message = "name is required")
String name;
@Valid // Nested Dto 검증하기 위해서 @Valid 어노테이션 추가!!!!
List<TeamDto> teamDto;
}
```

```java
class TeamDto {
@NotEmpty(message = "team name is required")
String name;
}
```

이렇게 멤버 변수에 @Valid 걸어주면 teamDto에 대한 validation도 수행된다:)

### Reference
https://medium.com/sjk5766/valid-vs-validated-%EC%A0%95%EB%A6%AC-5665043cd64b

0 comments on commit ad5eaa1

Please sign in to comment.