DRF: consistent API error handling with a custom exception handler

Backend Live Coding November 13, 2026 python

One error schema for the whole API (ideally RFC 9457 Problem Details).

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# ======================================================================
# Q: How do you handle errors consistently across the whole API?
#
# One error schema for the whole API (ideally RFC 9457 Problem Details).
# Business exceptions become proper status codes. 500s never show a stack trace
# to the client, they go to Sentry.
# ======================================================================

def api_exception_handler(exc, context):
    response = exception_handler(exc, context)      # DRF default
    if isinstance(exc, OutOfStock):
        return Response({'type': 'out_of_stock', 'title': 'Product out of stock',
                         'detail': str(exc)}, status=409)
    if response is not None:
        response.data = {'type': 'validation_error' if response.status_code == 400 else 'error',
                         'errors': response.data}
    return response

REST_FRAMEWORK = {'EXCEPTION_HANDLER': 'api.errors.api_exception_handler'}