728x90
반응형
1. Exception Handler 설정
Django에서 exception handler는 settings.py 파일의 RESTFRAMEWORK 설정에서 경로를 지정해줄 수 있다.
기본적으로는 Class를 지정하여 사용하며 exception_handler.ExceptionHandler를 상속받아 메서드들을 override한다.
from rest_framework.views import exception_handler
class CustomExceptionHandler(exception_handler.ExceptionHandler):
def handle_exception(self, exc):
# Custom logic to handle the exception
# Return a custom response with error details
response = ...
return response
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'myapp.exceptions.CustomExceptionHandler',
...
}
또는 아래처럼 그냥 함수로 지정해줘도 된다.
REST_FRAMEWORK = {
"EXCEPTION_HANDLER": "backend.utils.basic_exception_handler",
...
}
2. 사용법
exception 정보를 담고 있는 exc, 요청 정보를 담고있는 context 파라미터의 대략적인 구성은 아래와 같다.
그리고 rest_framework.views의 exception_handler를 통해 response를 받아와서 처리하면 된다.
def error_message_exception_handler(exc, context):
response = exception_handler(exc, context)
if isinstance(exc, Http404):
code = error_code.UnprocessableNotFoundError.default_code
elif isinstance(exc, ValidationError):
code = error_code.UnprocessableInvalidValue.default_code
return response
728x90
반응형
'Programming-[Backend] > Django' 카테고리의 다른 글
reverse relationship: _set 호출 시 get_ 메서드에서 N+1 발생 (0) | 2023.10.29 |
---|---|
API Throughput, health check fail: async 요청이 한 번에 많이 들어올 때 (0) | 2023.10.29 |
[TIL] Django Cache 개요 (0) | 2023.04.16 |
[TIL] Django ListSerializer 활용, List Update/Create (0) | 2023.03.20 |
[TIL] django, MYSQL, postgresql db collation (0) | 2023.02.15 |