1. Custom Exception Handler
- API의 에러 응답 스타일을 내 마음대로 바꾸어 사용하도록 하는 기능입니다.
DRF는 아래와 같이 에러 응답을 보여 줍니다.
{
"detail" : "error message"
}

error message 에 status_code 등을 추가하여 보여 주고 싶을 때
커스텀하여 보여줄 수 있는 기능이 Custom Exception Handler 입니다!
2. Custom Exception Handler 사용하기
먼저, 파일을 하나 만든 후 (utils.py) 문서에 있는 코드를 복사 붙여넣기 하였습니다.
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를 설정해야 합니다!
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
만약 지정하지 않을 경우 EXCEPTION_HANDLER 설정은 REST framework의 표준 EXCEPTION_HANDLER 로 기본 설정됩니다.
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}
settings.py를 설정한 후 다시 에러를 발생시켜 보았습니다!

status_code 필드가 추가된 상태로 잘 출력됩니다.
view에서 detail의 메세지를 변경하고 싶을 때는 이런 식으로 사용가능합니다.
if data is not None:
....
else
raise exceptions.NotFound("페이지가 없습니다!")
이렇게 출력됩니다.

Reference
https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling
Exceptions - Django REST framework
www.django-rest-framework.org
'웹 개발 > Django' 카테고리의 다른 글
django ORM > SQL 질의문 확인 방법 (0) | 2021.05.03 |
---|---|
Django orm (0) | 2021.05.03 |