티스토리 뷰

🐍/DRF

[DRF] 기본 Exception과 APIExecption

eungding 2020. 9. 24. 10:18
반응형

rest_framework에 있는 기본 exception과

 

 

 

APIException에 대해서 알아보겠습니다. 

 

 

 

[1] Exception 처리해야하는 이유

 

저의 SignupView는 이렇게 되어있는데요

아무 exception도 처리안해준 상태입니다. 

class SignupView(APIView):
    def post(self, request):
        unique_string = get_random_string(length=10)
        temporary_family_code = models.TemporaryFamilyCode(code=unique_string)

        user = User.objects.create_user(username=request.data['id'], password=request.data['password'])
        profile = models.Profile(user=user, nickname=request.data['nickname'], temporary_family_code=temporary_family_code)

        temporary_family_code.save()
        user.save()
        profile.save()

        token = Token.objects.create(user=user)
        return Response({"token": token.key, "nickname": profile.nickname, "temporary_family_code": profile.temporary_family_code.code})

 

예를 들어 id를 안보냈다고 했을때

아래와 처럼 html 에러가 납니다,,,, 

 

 

 

이런식으로 알맞은 status code와 detail을 응답해준다면 

클라이언트 쪽에서 이것을 보고 팝업을 띄우는등 예외처리하기 더 좋겠죠?!? 

 

 

 

[1] Exception

 

Exception문서에 보면 

Exception을 몇 종류 미리 만들어놨는데요 이것을 사용하면 됩니다. 

 

등등 있습니다. 문서에서 확인해주세요 

 

 

 

이렇게 import해주신다음 

from rest_framework import exceptions

 

raise로 exception을 발생시켜주면 됩니다. 

 

 

[2] APIException

 

APIException은 이미 지정된 exception말고 custom한 exception을 만들어서 쓰고 싶을때 사용합니다. 

 

 

예를 들어 이렇게 해주면 됩니다. 

 

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

 

위에서 썼던 exception을 APIException으로 한번 바꿔볼게요-!!

 

import 해주고 

from rest_framework.exceptions import APIException

 

Custom Exception을 만들어보겠습니다. 

 

 

그리고 raise로 exception을 일으켜주면 됩니다. 

 

 

그리고 key값을 빼먹고 요청을 해보면 

정의해둔 exception이 잘나옵니다.

default code는 안나오는 건가봐요,,!

 

 

 

 

 

 

Reference

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

 

Exceptions - Django REST framework

 

www.django-rest-framework.org

 

반응형
댓글