Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Submit week 4 assignment - Yeonjae #23

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

feat: Submit week 4 assignment - Yeonjae #23

wants to merge 2 commits into from

Conversation

Yeonjae37
Copy link
Contributor

@Yeonjae37 Yeonjae37 commented Jun 16, 2024

⭐ 과제 내용

  • Review API의 get, put, delete 메서드 구현 및 URL 연결

✅ PR Point

  • BookReviewDetailsView 클래스
    • get_book 메소드 : 예외 처리 후 book 객체 반환
    • get_review 메소드 : 예외 처리 후 review 객체 반환
    • get, put, delete 메소드 : 특정 id 책의 특정 review_id를 가진 리뷰를 조회, 수정, 삭제
  • urls.py=> review_id가 더해진 path 추가, class와 매핑

😡 트러블 슈팅

<문제 발생 코드>

def get_book(self, id):
    try:
        return Book.objects.get(id=id)
    except Book.DoesNotExist:
        return Response({'message': '도서를 찾지 못했습니다.'}, status=status.HTTP_400_BAD_REQUEST)

<발생 오류>

AttributeError at /books/7/reviews/
'Response' object has no attribute 'reviews'
Request Method:	GET

중복되는 코드를 처리하고자 예외 처리를 담당하는 get_book 과 get_reveiw를 만들었습니다.

request로 넘겨준 id에 해당하는 책이나 리뷰가 존재하지 않을 경우 AttributeError가 발생했습니다.

get_book 메소드를 호출하고, 책이 존재하지 않을 경우 Response 객체를 반환하기 때문에 오류가 발생했습니다.

클라이언트에게 상황에 맞는 오류 응답이 필요하다고 생각했습니다.

<해결 방법>

Response 객체를 반환하는 대신, Not Found 예외를 발생시켜 메소드의 나머지 부분이 실행되지 않고, 404 응답이 클라이언트에게 반환되도록 변경했습니다.

<문제 해결 코드>

    def get_book(self, id):
        try:
            return Book.objects.get(id=id)
        except Book.DoesNotExist:
            raise NotFound({'message': '도서를 찾지 못했습니다.'})

https://www.django-rest-framework.org/api-guide/exceptions/#notfound

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant