본문 바로가기

TIL

TIL 240610 예외 처리 변경

1. 예외처리

 

변경전

Post post = postRepository.findById(id).orElseThrow(()-> new IllegalArgumentException("잘못된 POST ID"));

 

 변경 후

Post post = findPostById(id);

 

public Post findPostById(Long id) {
    return  postRepository.findById(id).orElseThrow(()-> new CommonException(
        ErrorStatus.POST_ID_NOT_FOUND));
}

예외 처리 로직이 'findPostById(Long id) 라는 별도의 메서드로 이동

효과 : 예외 처리 로직을 중앙 집중화하여 가독성과 재사용성을 향상 시켰다

 

2. 어노테이션 변경

변경 전 : @AllArgsConstructor

변경 후 : @RequiredArgsConstructor

후자는 모든 final 필드에 대한 생성자를 생성하여 필수 종속성이 주입되도록 보장하며, @AllArgsConstructor는 모든 필드에 대한 생성자를 생성합니다.

 

3. 예외 클래스

 

  • 변경 전: 코드에서는 IllegalArgumentException을 사용했습니다.
  • 변경 후: 커스텀 예외 CommonException을 사용했습니다:
import com.sparta.lck_news.exception.CommonException;
import com.sparta.lck_news.exception.ErrorStatus;

 

이를 통해 더 구체적이고 명확한 예외 처리를 할 수 있습니다

 

 

변경 전 코드

package com.sparta.lck_news.service;

import com.sparta.lck_news.dto.PostCreateRequest;
import com.sparta.lck_news.dto.PostResponse;
import com.sparta.lck_news.entity.Post;
import com.sparta.lck_news.repository.PostRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@AllArgsConstructor
public class PostService {

    private final PostRepository postRepository;

    @Transactional(readOnly = true)
    public List<Post> getAllPost() {
        return postRepository.findAll();
    }

    @Transactional(readOnly = true)
    public PostResponse getPostById(Long id) {
        Post post = postRepository.findById(id).orElseThrow(()-> new IllegalArgumentException("잘못된 POST ID"));
        return new PostResponse(post);
    }

    @Transactional
    public Post createPost(PostCreateRequest post) {
        return postRepository.save(post.toEntity());
    }

    @Transactional
    public Post updatePost(Long id, PostCreateRequest updatedPost) {
        Post post = postRepository.findById(id).orElseThrow(()-> new IllegalArgumentException("잘못된 Post ID"));
        post.update(updatedPost.getContent());

        return postRepository.save(post);
    }

    @Transactional
    public void deletePost(Long id) {
        postRepository.deleteById(id);
    }
}

 


변경 후 코드

package com.sparta.lck_news.service;


import com.sparta.lck_news.dto.PostCreateRequest;
import com.sparta.lck_news.dto.PostResponse;
import com.sparta.lck_news.entity.Post;
import com.sparta.lck_news.exception.CommonException;
import com.sparta.lck_news.exception.ErrorStatus;
import com.sparta.lck_news.repository.PostRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@RequiredArgsConstructor
public class PostService {

    private final PostRepository postRepository;

    @Transactional(readOnly = true)
    public List<Post> getAllPost() {
        return postRepository.findAll();
    }

    @Transactional(readOnly = true)
    public PostResponse getPostById(Long id) {
        Post post = findPostById(id);
        return new PostResponse(post);
    }

    @Transactional
    public Post createPost(PostCreateRequest post) {
        return postRepository.save(post.toEntity());
    }

    @Transactional
    public Post updatePost(Long id, PostCreateRequest updatedPost) {
        Post post = findPostById(id);
        post.update(updatedPost.getContent());

        return postRepository.save(post);
    }

    @Transactional
    public void deletePost(Long id) {
        postRepository.deleteById(id);
    }

    public Post findPostById(Long id) {
        return  postRepository.findById(id).orElseThrow(()-> new CommonException(
            ErrorStatus.POST_ID_NOT_FOUND));
    }

}

 

 

이와 같은 변경사항을 통해서 코드의 가독성과 유지 보수성이 향상되었음

 

'TIL' 카테고리의 다른 글

TIL 240612 카카오 로그인  (1) 2024.06.13
TIL 240611 3조 KPT 회고  (0) 2024.06.12
TIL 240607 Spring Request Mapping  (0) 2024.06.10
TIL 240605 HTTP Request Parameter  (0) 2024.06.07
TIL 240604 Annotation  (0) 2024.06.05