53 lines
1.5 KiB
Python
53 lines
1.5 KiB
Python
"""
|
|
Custom exception handler for DRF.
|
|
"""
|
|
|
|
from rest_framework.views import exception_handler
|
|
from rest_framework.response import Response
|
|
from rest_framework import status
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def custom_exception_handler(exc, context):
|
|
"""
|
|
Custom exception handler that provides consistent error responses.
|
|
|
|
Handles common exceptions and formats them consistently.
|
|
"""
|
|
# Call REST framework's default exception handler first
|
|
response = exception_handler(exc, context)
|
|
|
|
if response is not None:
|
|
# Customize the response data
|
|
custom_response_data = {
|
|
'error': True,
|
|
'status_code': response.status_code,
|
|
}
|
|
|
|
if isinstance(response.data, dict):
|
|
if 'detail' in response.data:
|
|
custom_response_data['message'] = str(response.data['detail'])
|
|
else:
|
|
custom_response_data['errors'] = response.data
|
|
elif isinstance(response.data, list):
|
|
custom_response_data['errors'] = response.data
|
|
else:
|
|
custom_response_data['message'] = str(response.data)
|
|
|
|
response.data = custom_response_data
|
|
return response
|
|
|
|
# Handle unexpected exceptions
|
|
logger.exception(f"Unhandled exception: {exc}")
|
|
|
|
return Response(
|
|
{
|
|
'error': True,
|
|
'status_code': 500,
|
|
'message': 'An unexpected error occurred',
|
|
},
|
|
status=status.HTTP_500_INTERNAL_SERVER_ERROR
|
|
)
|