32 lines
1.3 KiB
Python
32 lines
1.3 KiB
Python
"""
|
||
هندلرِ سفارشیِ exception برای DRF: هندلرِ پیشفرض فقط APIException/Http404/
|
||
PermissionDenied رو میشناسه؛ برای بقیه None برمیگردونه و exception خام تا
|
||
مدیریتِ خطای جنگو بالا میره که (DEBUG=False) یه صفحهی HTML عمومی میده، نه
|
||
JSON. این هندلر اون حالت رو با traceback کامل لاگ میکنه و یه پاسخِ JSON
|
||
ژنریکِ ۵۰۰ برمیگردونه.
|
||
"""
|
||
import logging
|
||
|
||
from rest_framework.response import Response
|
||
from rest_framework.views import exception_handler as drf_exception_handler
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
def custom_exception_handler(exc, context):
|
||
response = drf_exception_handler(exc, context)
|
||
if response is not None:
|
||
return response
|
||
|
||
request = context.get('request')
|
||
user = getattr(request, 'user', None)
|
||
user_id = user.id if getattr(user, 'is_authenticated', False) else None
|
||
logger.exception(
|
||
'unhandled_exception path=%s user_id=%s',
|
||
getattr(request, 'path', ''), user_id,
|
||
)
|
||
return Response(
|
||
{'detail': 'خطای غیرمنتظرهای رخ داد؛ لطفاً بعداً دوباره تلاش کنید.'},
|
||
status=500,
|
||
)
|