DRF Exceptions Hog

0.4.0 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

To integrate drf-exceptions-hog, update your Django REST Framework settings in your `settings.py` file to use `exceptions_hog.exception_handler` as the default exception handler. Optionally, you can configure `ENABLE_IN_DEBUG` to control its behavior in development mode.

# 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)

view raw JSON →