Skip to content

Commit 3e2a37c

Browse files
committed
Add custom exception handler for Django REST Framework
Add a custom exception handler to wrap all exceptions that are not handled by the REST framework's default exception handler into a JSON response with a 500 Internal Server Error HTTP status code.
1 parent 269a201 commit 3e2a37c

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

promgen/middleware.py

+19-1
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,15 @@
1818
"""
1919

2020
import logging
21+
from http import HTTPStatus
2122
from threading import local
2223

2324
from django.contrib import messages
2425
from django.db.models import prefetch_related_objects
26+
from django.http import JsonResponse
27+
from rest_framework import views, exceptions
2528

26-
from promgen import models
29+
from promgen import models, settings
2730
from promgen.signals import trigger_write_config, trigger_write_rules, trigger_write_urls
2831

2932
logger = logging.getLogger(__name__)
@@ -67,3 +70,18 @@ def __call__(self, request):
6770

6871
def get_current_user():
6972
return getattr(_user, "value", None)
73+
74+
75+
def custom_exception_handler(exc, context):
76+
# Call REST framework's default exception handler first,
77+
# to get the standard error response.
78+
response = views.exception_handler(exc, context)
79+
80+
if response is None:
81+
# If an exception is raised that we don't handle, we will return a 500 error
82+
# with the exception message. This is useful for debugging in development
83+
if settings.DEBUG:
84+
return JsonResponse({"detail": str(exc)}, status=HTTPStatus.INTERNAL_SERVER_ERROR)
85+
return exceptions.server_error(context["request"])
86+
87+
return response

promgen/settings.py

+1
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@
198198
),
199199
"DEFAULT_FILTER_BACKENDS": ("django_filters.rest_framework.DjangoFilterBackend",),
200200
"DEFAULT_SCHEMA_CLASS": "promgen.schemas.CustomSchema",
201+
"EXCEPTION_HANDLER": "promgen.middleware.custom_exception_handler",
201202
}
202203

203204
# If CELERY_BROKER_URL is set in our environment, then we configure celery as

0 commit comments

Comments
 (0)