diff --git a/src/main/java/com/cnu/real_coding_server/RealCodingServerApplication.java b/src/main/java/com/cnu/real_coding_server/RealCodingServerApplication.java index fc49dd5..6e4c715 100644 --- a/src/main/java/com/cnu/real_coding_server/RealCodingServerApplication.java +++ b/src/main/java/com/cnu/real_coding_server/RealCodingServerApplication.java @@ -6,8 +6,7 @@ @EnableJpaAuditing @SpringBootApplication -public class RealCodingServerApplication { - +public class RealCodingServerApplication public static void main(String[] args) { SpringApplication.run(RealCodingServerApplication.class, args); } diff --git a/src/main/java/com/cnu/real_coding_server/controller/PostController.java b/src/main/java/com/cnu/real_coding_server/controller/PostController.java index c31c90e..67bd2e8 100644 --- a/src/main/java/com/cnu/real_coding_server/controller/PostController.java +++ b/src/main/java/com/cnu/real_coding_server/controller/PostController.java @@ -42,4 +42,10 @@ public ResponseEntity deletePost(@PathVariable("postId") Integer postId) { return ResponseEntity.noContent().build(); } + + @ExceptionHandler(ResourceNotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public String handleResourceNotFoundException(ResourceNotFoundException exception) { + return exception.getMessage(); + } } diff --git a/src/main/java/com/cnu/real_coding_server/service/PostService.java b/src/main/java/com/cnu/real_coding_server/service/PostService.java index 490a745..c47da9f 100644 --- a/src/main/java/com/cnu/real_coding_server/service/PostService.java +++ b/src/main/java/com/cnu/real_coding_server/service/PostService.java @@ -24,21 +24,25 @@ public List getPosts() { } public Optional getPost(Integer postId) { - return postRepository.findById(postId); + return postRepository.findById(postId) + .orElseThrow(() -> new ResourceNotFoundException("Post not found with id: " + postId)); } public Optional updatePost(Integer postId, PostRequest postRequest) { - return postRepository.findById(postId) - .map(post -> { - post.setTitle(postRequest.getTitle()); - post.setContents(postRequest.getContents()); - post.setTag(postRequest.getTag()); - return postRepository.save(post); - }); + Post post = postRepository.findById(postId) + .orElseThrow(() -> new ResourceNotFoundException("Post not found with id: " + postId)); + + post.setTitle(postRequest.getTitle()); + post.setContents(postRequest.getContents()); + post.setTag(postRequest.getTag()); + + return Optional.of(postRepository.save(post)); } public void deletePost(Integer postId) { - postRepository.findById(postId) - .ifPresent(postRepository::delete); + Post post = postRepository.findById(postId) + .orElseThrow(() -> new ResourceNotFoundException("Post not found with id: " + postId)); + + postRepository.delete(post); } }