← Back to Django, page 4

django-0080 · Medium mid

How do you give a Django REST Framework API a consistent error format using a custom exception handler?

DRF converts APIException subclasses and Django's Http404 and PermissionDenied into responses through the function named by REST_FRAMEWORK['EXCEPTION_HANDLER']. A custom handler calls the default exception_handler(), then reshapes response.data into a single envelope, and can convert unexpected exceptions into a generic 500 while logging details. A stable error shape makes clients simpler.

Full answer

By default, errors look different per source: validation gives {"name": ["This field is required."]}, other exceptions give {"detail": "Not found."}. Clients then need several parsers.

A custom handler:

python
def api_exception_handler(exc, context):
    response = exception_handler(exc, context)         # DRF's default handler
    if response is None:                                # not an APIException, Http404 or PermissionDenied
        logger.exception("Unhandled error", extra={"view": context["view"].__class__.__name__})
        return Response({"error": {"code": "server_error", "message": "Something went wrong."}}, status=500)
    response.data = {"error": {"code": ..., "message": ..., "fields": ...}}
    return response

Configure: REST_FRAMEWORK = {"EXCEPTION_HANDLER": "myapp.errors.api_exception_handler"}.

Details:

  • exception_handler() returns None for exceptions it does not handle (anything other than APIException, Http404 and PermissionDenied). If your handler also returns None, DRF re-raises, so Django answers with its own 500 and error reporting sees the exception. Returning your own 500 response, as above, gives uniform JSON, but then you must log the exception yourself.
  • exc.get_codes() gives machine-readable codes (required, invalid), and exc.detail holds text, possibly nested. Do not leak internal messages for unexpected exceptions.
  • Add request_id or a documentation URL to the envelope for supportability. Consider RFC 9457 application/problem+json for a standard format.
  • Domain errors: define class DomainError(APIException) with status_code, default_detail and default_code, and raise them from services; the handler formats them.
  • Wrap with ATOMIC_REQUESTS carefully: DRF's handler marks the transaction for rollback with set_rollback() when a request is under ATOMIC_REQUESTS.
  • Test the shape for 400, 401, 403, 404, 405, 429 and 500 so the contract does not drift.
python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    ROOT_URLCONF=__name__,
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "rest_framework", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.urls import path
from rest_framework import serializers, status
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework.test import APIClient
from rest_framework.views import APIView, exception_handler
from rest_framework.settings import api_settings


def api_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if response is None:
        return Response({"error": {"code": "server_error", "message": "Something went wrong."}}, status=500)
    data = response.data
    if isinstance(data, dict) and set(data) != {"detail"}:
        error = {"code": "validation_error", "message": "Some fields are invalid.", "fields": data}
    else:
        detail = data["detail"]
        error = {"code": getattr(detail, "code", "error"), "message": str(detail)}
    response.data = {"error": error}
    return response


settings.REST_FRAMEWORK = {"EXCEPTION_HANDLER": "__main__.api_exception_handler"}
api_settings.reload()          # the settings object caches values, so reload after changing them at run time


class FeeClosed(APIException):
    status_code = status.HTTP_409_CONFLICT
    default_detail = "Fee window is closed."
    default_code = "fee_window_closed"


class In(serializers.Serializer):
    amount = serializers.IntegerField(min_value=1)


class Pay(APIView):
    def post(self, request, mode):
        if mode == "closed":
            raise FeeClosed()
        if mode == "boom":
            raise RuntimeError("database password is hunter2")
        In(data=request.data).is_valid(raise_exception=True)
        return Response({"ok": True})


urlpatterns = [path("pay/<str:mode>/", Pay.as_view())]
c = APIClient(raise_request_exception=False)
for mode, body in [("ok", {"amount": 0}), ("closed", {"amount": 5}), ("boom", {"amount": 5}), ("ok", {"amount": 5})]:
    r = c.post(f"/pay/{mode}/", body, format="json")
    print(r.status_code, r.json())
print(c.get("/pay/ok/").status_code, c.get("/pay/ok/").json())

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Requires `pip install djangorestframework`. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 400 {'error': {'code': 'validation_error', 'message': 'Some fields are invalid.', 'fields': {'amount': ['Ensure this value is greater than or equal to 1.']}}} 409 {'error': {'code': 'fee_window_closed', 'message': 'Fee window is closed.'}} 500 {'error': {'code': 'server_error', 'message': 'Something went wrong.'}} 200 {'ok': True} 405 {'error': {'code': 'method_not_allowed', 'message': 'Method "GET" not allowed.'}}

Key points

  • Default error shapes differ by source
  • Wrap exception_handler() and reshape response.data
  • Returning None makes DRF re-raise, so Django answers with a 500
  • Domain errors can subclass APIException
  • Test every error status for contract stability

Common mistakes

  • Leaking exception messages from unexpected errors to clients
  • Returning different error shapes from different endpoints
  • Swallowing unexpected exceptions without logging
  • Forgetting to test non-validation errors such as 405 and 429

Follow-ups

  • How does RFC 9457 problem details compare to a custom envelope?
  • How would you attach a request ID to every error?
  • What does the handler receive in context?

Tips

  • Describe wrapping the default handler
  • Mention the None return for unknown exceptions
  • Mention domain exceptions