From ad5eaa1070c5081c63e8e0df7fdb50d54cf9ab27 Mon Sep 17 00:00:00 2001 From: suzieep Date: Mon, 26 Feb 2024 20:21:58 +0900 Subject: [PATCH] =?UTF-8?q?240226=20@Valid=20Nested=20Dto=20=EA=B2=80?= =?UTF-8?q?=EC=A6=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TIL/240221.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ TIL/240226.md | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 TIL/240221.md create mode 100644 TIL/240226.md diff --git a/TIL/240221.md b/TIL/240221.md new file mode 100644 index 0000000..bd3fc8b --- /dev/null +++ b/TIL/240221.md @@ -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 handleMethodArgumentNotValid(MethodArgumentNotValidException ex) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("name is required"); + } +} +``` \ No newline at end of file diff --git a/TIL/240226.md b/TIL/240226.md new file mode 100644 index 0000000..42b9720 --- /dev/null +++ b/TIL/240226.md @@ -0,0 +1,37 @@ +# 240226 @Valid Nested Dto 검증 + +## 겪은 문제 +- @Valid 어노테이션을 사용하는데, Nested Dto에 대한 validation이 안됐다!! + + +## 해결 방법 예시 코드 + +```java +class MemberController { + @PostMapping("/member") + public ResponseEntity 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; +} +``` + +```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 \ No newline at end of file