forked from prgrms-be-devcourse/springboot-board-jpa
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
#4 feat: binding result에 따른 검증 로직 컨트롤러에 추가
- Loading branch information
Showing
1 changed file
with
33 additions
and
1 deletion.
There are no files selected for viewing
34 changes: 33 additions & 1 deletion
34
src/main/java/com/example/board/controller/PostController.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,55 @@ | ||
package com.example.board.controller; | ||
|
||
import com.example.board.dto.PostDto; | ||
import com.example.board.exception.BaseException; | ||
import com.example.board.exception.BindingException; | ||
import com.example.board.exception.ErrorMessage; | ||
import com.example.board.response.Response; | ||
import com.example.board.service.PostService; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.http.HttpStatus; | ||
import org.springframework.http.ResponseEntity; | ||
import org.springframework.validation.BindingResult; | ||
import org.springframework.validation.FieldError; | ||
import org.springframework.validation.ObjectError; | ||
import org.springframework.validation.annotation.Validated; | ||
import org.springframework.web.bind.annotation.PostMapping; | ||
import org.springframework.web.bind.annotation.RequestBody; | ||
import org.springframework.web.bind.annotation.RequestMapping; | ||
import org.springframework.web.bind.annotation.RestController; | ||
|
||
import java.util.List; | ||
|
||
@RequiredArgsConstructor | ||
@RequestMapping("/api/v1/posts") | ||
@RestController | ||
public class PostController { | ||
private final PostService postService; | ||
|
||
@PostMapping | ||
public Response<Long> save(@RequestBody PostDto postDto) { | ||
public Response<Long> save(@RequestBody @Validated PostDto postDto, BindingResult bindingResult) { | ||
bindChecking(bindingResult); | ||
return Response.success(postService.save(postDto)); | ||
} | ||
|
||
private static void bindChecking(BindingResult bindingResult) { | ||
if (bindingResult.hasErrors()) { | ||
StringBuilder sb = new StringBuilder(); | ||
bindingResult.getAllErrors().forEach(objectError -> { | ||
|
||
FieldError field = (FieldError) objectError; | ||
String message = objectError.getDefaultMessage(); | ||
|
||
System.out.println("field :" + field.getField()); | ||
System.out.println("message :" + message); | ||
|
||
sb.append("field :" + field.getField()); | ||
sb.append("message :" + message); | ||
|
||
}); | ||
|
||
throw new BindingException(sb.toString()); | ||
} | ||
} | ||
|
||
} |