DRF Exceptions Hog
DRF Exceptions Hog provides standardized and easy-to-parse API error responses for Django REST Framework. It aims to unify the format of exceptions to simplify frontend parsing logic. The current version is 0.4.0, and it is actively maintained by PostHog with a moderate release cadence.
Warnings
- gotcha By default, `drf-exceptions-hog` is disabled when `DEBUG=True` in Django settings. This is intentional to allow developers to see full stack traces for debugging. To enable standardized error responses even in debug mode, you must explicitly set `DRF_EXCEPTIONS_HOG = {"ENABLE_IN_DEBUG": True}` in your `settings.py`.
- gotcha Versions prior to `0.0.5` lacked explicit support for handling exceptions from deeply nested serializers, which could lead to inconsistent or incomplete error response formats for complex validation scenarios.
- gotcha Older versions might have encountered a `KeyError` when processing serializer validation errors that included the `__all__` key (used for non-field errors, e.g., from unique constraints or `full_clean` on a model). This issue was addressed in a fix related to GitHub issue #12.
- gotcha In production (when `DEBUG=False`), `drf-exceptions-hog` intentionally returns a generic 'A server error occurred.' for unhandled 5xx exceptions. This is a security measure to prevent sensitive information leakage (e.g., raw tracebacks, internal paths). For detailed error reporting, integrate with an error monitoring tool like Sentry.
Install
-
pip install drf-exceptions-hog
Imports
- exception_handler
REST_FRAMEWORK = { "EXCEPTION_HANDLER": "exceptions_hog.exception_handler" }
Quickstart
# settings.py
INSTALLED_APPS = [
# ...
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
# 'exceptions_hog' is not strictly required in INSTALLED_APPS
# if only using the handler, but good practice if it has models/migrations.
# For drf-exceptions-hog, it usually isn't needed.
]
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'exceptions_hog.exception_handler',
# Optional: Enable in DEBUG mode to see standardized errors even during development.
# By default, it's disabled when DEBUG=True to allow full stack traces.
# 'DRF_EXCEPTIONS_HOG': {'ENABLE_IN_DEBUG': True}
}
# views.py (example usage for testing)
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.exceptions import ValidationError
class ExampleView(APIView):
def get(self, request):
if request.query_params.get('error'):
raise ValidationError({'field': 'This is a validation error.'})
if request.query_params.get('server_error'):
1 / 0 # Simulate an unhandled server error
return Response({"message": "Hello, world!"}, status=status.HTTP_200_OK)