Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
runtimeOnly 'com.h2database:h2'
implementation 'org.springframework.boot:spring-boot-starter-validation'
// Swagger 의존성
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.5'
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.example.leets_project.common.exception;

import com.example.leets_project.common.response.ErrorCode;
import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class GeneralException extends RuntimeException{

private ErrorCode errorCode;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.example.leets_project.common.exception;

import com.example.leets_project.common.response.ErrorCode;
import com.example.leets_project.common.response.GlobalResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

// 커스텀 예외
@ExceptionHandler(GeneralException.class)
public ResponseEntity<GlobalResponse> handleGeneralException(GeneralException e) {
log.warn("GeneralException: [{}] {}", e.getErrorCode().getCode(), e.getErrorCode().getMessage());
return GlobalResponse.onFailure(e.getErrorCode());
}
// Validation 에러
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<GlobalResponse> handleValidationExceptions(MethodArgumentNotValidException e) {
String errorDetail = e.getBindingResult()
.getFieldErrors()
.stream()
.map(error -> "[" + error.getField() + "]: " + error.getDefaultMessage())
.collect(Collectors.joining(", "));

log.warn("Validation Failed: {}", errorDetail);
return GlobalResponse.onFailure(ErrorCode.VALIDATION_FAILED, errorDetail);
}

// JSON 처리 에러
@ExceptionHandler({com.fasterxml.jackson.core.JsonParseException.class,
com.fasterxml.jackson.databind.JsonMappingException.class})
public ResponseEntity<GlobalResponse> handleJsonException(Exception e) {
log.error("JSON 처리 오류: {}", e.getMessage());

return GlobalResponse.onFailure(ErrorCode.VALIDATION_FAILED, "잘못된 JSON 형식입니다.");
}

// X-USER-ID 헤더 누락
@ExceptionHandler(MissingRequestHeaderException.class)
public ResponseEntity<GlobalResponse> handleMissingHeader(MissingRequestHeaderException e) {
log.warn("필수 헤더 누락 - {}", e.getHeaderName());

return GlobalResponse.onFailure(ErrorCode.UNAUTHORIZED, "필수 헤더가 누락되었습니다.");
}

// 모든 예외
@ExceptionHandler(Exception.class)
public ResponseEntity<GlobalResponse> handleGenericException(Exception e) {
log.error("Unexpected Error", e);

return GlobalResponse.onFailure(ErrorCode.INTERNAL_ERROR);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.example.leets_project.common.response;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.http.HttpStatus;

@Getter
@AllArgsConstructor
public enum ErrorCode {

// COMMON
VALIDATION_FAILED(HttpStatus.BAD_REQUEST, "COMMON_4000", "유효하지 않은 값입니다."),
INVALID_INPUT(HttpStatus.BAD_REQUEST, "COMMON_4001", "잘못된 입력입니다."),
METHOD_NOT_ALLOWED(HttpStatus.METHOD_NOT_ALLOWED, "COMMON_4002", "허용되지 않은 요청입니다."),
INTERNAL_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON_5000", "서버 오류입니다."),

// AUTH
UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "AUTH_4000", "인증이 필요합니다."),
FORBIDDEN(HttpStatus.FORBIDDEN, "AUTH_4001", "접근 권한이 없습니다."),

// USER
USER_NOT_FOUND(HttpStatus.NOT_FOUND, "USER_4040", "사용자를 찾을 수 없습니다."),
USER_EMAIL_ALREADY_EXISTS(HttpStatus.CONFLICT, "USER_4001", "이미 사용 중인 이메일입니다."),
USER_NICKNAME_ALREADY_EXISTS(HttpStatus.CONFLICT, "USER_4002", "이미 사용 중인 닉네임입니다."),
// POST
POST_NOT_FOUND(HttpStatus.NOT_FOUND, "POST_4040", "게시글을 찾을 수 없습니다."),
POST_INVALID(HttpStatus.BAD_REQUEST, "POST_4001", "게시글 입력값이 올바르지 않습니다."),
POST_FORBIDDEN(HttpStatus.FORBIDDEN, "POST_4003", "작성자만 수정/삭제할 수 있습니다.");

private final HttpStatus status;
private final String code;
private final String message;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.example.leets_project.common.response;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;

@Getter
@RequiredArgsConstructor
@JsonPropertyOrder({"isSuccess", "code", "message", "result"})
public class GlobalResponse {

private final Boolean isSuccess; // 성공, 실패 여부

private final String code; // 상태 코드

private final String message; // 구체적인 메시지

@JsonInclude(JsonInclude.Include.NON_NULL)
private final Object result; //반환할 객체

public static ResponseEntity<GlobalResponse> onSuccess(SuccessCode successCode, Object result){
return new ResponseEntity<>(
new GlobalResponse(true, successCode.getCode(), successCode.getMessage(), result),
successCode.getStatus());
}

public static ResponseEntity<GlobalResponse> onSuccess(SuccessCode successCode){
return new ResponseEntity<>(
new GlobalResponse(true, successCode.getCode(), successCode.getMessage(), null),
successCode.getStatus());
}

public static ResponseEntity<GlobalResponse> onFailure(ErrorCode errorCode, Object result){
return new ResponseEntity<>(
new GlobalResponse(false, errorCode.getCode(), errorCode.getMessage(), result),
errorCode.getStatus());
}

public static ResponseEntity<GlobalResponse> onFailure(ErrorCode errorCode){
return new ResponseEntity<>(
new GlobalResponse(false, errorCode.getCode(), errorCode.getMessage(), null),
errorCode.getStatus());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.example.leets_project.common.response;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.http.HttpStatus;

@Getter
@AllArgsConstructor
public enum SuccessCode {

// USER
USER_CREATE(HttpStatus.CREATED, "USER_2010", "유저 생성 성공"),
// POST
POST_LIST(HttpStatus.OK, "POST_2000", "게시글 목록 조회 성공"),
POST_DETAIL(HttpStatus.OK, "POST_2001", "게시글 조회 성공"),
POST_UPDATE(HttpStatus.OK, "POST_2002", "게시글 수정 성공"),
POST_DELETE(HttpStatus.OK, "POST_2003", "게시글 삭제 성공"),
POST_CREATE(HttpStatus.CREATED, "POST_2010", "게시글 생성 성공");

private final HttpStatus status;
private final String code;
private final String message;
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
package com.example.leets_project.domain.comment;

import com.example.leets_project.common.entity.BaseEntity;
import com.example.leets_project.domain.post.Post;
import com.example.leets_project.domain.post.entity.Post;
import com.example.leets_project.domain.user.User;
import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;

@Entity
@Table(name = "comments")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
package com.example.leets_project.domain.post;
package com.example.leets_project.domain.post.entity;

import com.example.leets_project.common.entity.BaseEntity;
import com.example.leets_project.common.exception.GeneralException;
import com.example.leets_project.common.response.ErrorCode;
import com.example.leets_project.domain.comment.Comment;
import com.example.leets_project.domain.user.User;
import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

Expand Down Expand Up @@ -49,4 +48,16 @@ public Post(User user, String title, String content, String description) {
this.content = content;
this.description = description;
}
public void updatePost(String title, String content, String description, Long requesterId) {
validateOwner(requesterId);
this.title = title;
this.content = content;
this.description = description;
}

public void validateOwner(Long userId) {
if (!this.user.getId().equals(userId)) {
throw new GeneralException(ErrorCode.POST_FORBIDDEN);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.example.leets_project.domain.post.repository;

import com.example.leets_project.domain.post.entity.Post;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PostRepository extends JpaRepository<Post, Long> {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package com.example.leets_project.domain.post.service;

import com.example.leets_project.common.exception.GeneralException;
import com.example.leets_project.common.response.ErrorCode;
import com.example.leets_project.domain.post.entity.Post;
import com.example.leets_project.domain.post.repository.PostRepository;
import com.example.leets_project.domain.post.web.dto.*;
import com.example.leets_project.domain.user.User;
import com.example.leets_project.domain.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class PostService {

private final PostRepository postRepository;
private final UserRepository userRepository;

private static final int MIN_PAGE = 0;
private static final int MAX_PAGE = 10;

// 1. 게시글 생성
@Transactional
public PostCreateResponse createPost(Long currentUserId, PostCreateRequest request) {
// 사용자 존재 확인
User user = findUserOrThrow(currentUserId);

Post post = Post.builder()
.user(user)
.title(request.getTitle())
.content(request.getContent())
.description(request.getDescription())
.build();

Post savedPost = postRepository.save(post);

return PostCreateResponse.from(savedPost);
}

// 2. 게시글 목록 조회 (페이징)
public Page<PostListResponse> getPosts(int page, int size) {

validatePageRange(page);
PageRequest pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));

return postRepository.findAll(pageable)
.map(PostListResponse::from);
}

// 3. 게시글 상세 조회
public PostDetailResponse getPostDetail(Long postId) {

Post post = findPostOrThrow(postId);

return PostDetailResponse.from(post);
}

// 4. 게시글 수정
@Transactional
public PostUpdateResponse updatePost(Long postId, Long currentUserId, PostUpdateRequest request) {

Post post = findPostOrThrow(postId);

post.updatePost(
request.getTitle(),
request.getContent(),
request.getDescription(),
currentUserId
);

return PostUpdateResponse.from(post);
}

// 5. 게시글 삭제
@Transactional
public PostDeleteResponse deletePost(Long postId, Long currentUserId) {

Post post = findPostOrThrow(postId);

post.validateOwner(currentUserId);

postRepository.delete(post);

return PostDeleteResponse.of(postId);
}

// 공통 검증 로직
// 게시글 조회
private Post findPostOrThrow(Long postId) {
return postRepository.findById(postId)
.orElseThrow(() -> new GeneralException(ErrorCode.POST_NOT_FOUND));
}

// 사용자 조회
private User findUserOrThrow(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new GeneralException(ErrorCode.USER_NOT_FOUND));
}

private void validatePageRange(int page) {
if (page < MIN_PAGE || page > MAX_PAGE) {
throw new GeneralException(ErrorCode.POST_INVALID);
}
}
Comment on lines +93 to +110
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 게시글이 존재하는지, 사용자가 존재하는지에 대한 검증 코드를 매번 메소드마다 따로 작성했었는데, 이렇게 자주 사용하는 검증 코드를 메소드로 만들어두고 쓰면 가독성도 더 좋고 확장하기도 편할 것 같습니다. 고생 많으셨습니다!

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

존재하지 않는 id인 경우에 커스텀 예외로 던지고, 전역 핸들러에서 처리하는 구조도 좋은 것 같습니다. 코드 참고해서 피드백 주신 부분 보완해보겠습니다!

}
Loading