error-handling: add global exception handling, guard Bazaar API calls

This commit is contained in:
2026-08-26 03:22:20 +03:30
parent 49d596f077
commit 83435c5a5f
4 changed files with 110 additions and 15 deletions

31
config/exceptions.py Normal file
View File

@@ -0,0 +1,31 @@
"""
هندلرِ سفارشیِ 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,
)