본문 바로가기
AI 웹개발반/Python, Django

[DRF] APIView와 exception handler (2)

by 째깍단 2024. 1. 26.

참고 : 

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

 

Exceptions - Django REST framework

 

www.django-rest-framework.org

 

 

Django rest framework에서의 예외 처리

처리되는 예외는 기본적으로 3가지가 구현되어있고, 적절한 상태코드와 메세지(detail)를 반환한다

 

1. REST framework 내의 APIException 에러들

2. Django의 Http404

3. Django의 PermissionDenied 

 

 

Custom exception handler 예제

 

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status_code'] = response.status_code

    return response

 

 

 


 

 

 

settings.py에서 exception handler를 바꾸어 적용해준다.

 

REST_FRAMEWORK에 작성되어있지 않더라도 기본적으로 내장된 exception handler로 처리되게 설정되어있다.

#지정하지 않으면 기본적으로 REST 프레임워크에서 제공하는 표준 예외 처리기가 설정됩니다.
REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}

 

 

 

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}

 

 

아래와 같이 config 폴더에 utils폴더 - api_exceptions.py를 추가했을 경우

 

루트를 기준으로 경로를 작성해주면 된다.

 

 

 


 

이후 같은 함수에

exceptions.py에 준비되어있는 에러들 중 필요한 것을 오버라이딩하여 exception을 handling할 수 있다.

 

def custom_exception_handler(exc, context):
	...

    if isinstance(exc, InvalidSignatureError):
        return Response("Unauthorized", status=status.HTTP_401_UNAUTHORIZED)
	...

 

exceptions.py의 에러들