Django 6.1.3

3.4 Handlers, middleware, and async

Exception walls and error responses

Why does an exception raised inside a view become a 404 or 500 response before outer middleware ever sees it?

Every Django developer eventually tries to write an error-tracking or JSON-formatting middleware like this:

class NaiveCatchMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            return self.get_response(request)
        except Http404:
            return JsonResponse({"error": "not found"}, status=404)

Deploy it, hit a missing story URL, and the except Http404 branch never runs. Calling get_response does not raise Http404; it quietly returns a normal HttpResponseNotFound with status 404. Even an unhandled RuntimeError inside a view comes back to outer middleware as a 500 HttpResponseServerError instead of propagating up the stack.

That behaviour is not an accident. It is enforced by an exception boundary wrapped around every single ring of the middleware onion by convert_exception_to_response.

An armor wall around every single layer

Look back at BaseHandler.load_middleware. Line 39 wraps the core (_get_response or _get_response_async) inside convert_exception_to_response(get_response), and line 97 wraps every individual middleware instance inside convert_exception_to_response(mw_instance) before handing it to the next outer layer.

Because of those two lines, DEP 0005’s strongest guarantee holds unconditionally: when any middleware invokes its inner get_response callable, it is guaranteed to receive an HttpResponse back — never an ordinary Exception.

Open lines 25–62 of django/core/handlers/exception.py. convert_exception_to_response inspects iscoroutinefunction(get_response) and returns either an async def inner(request) or a synchronous def inner(request) that runs get_response(request) inside try / except Exception as exc:. If an Exception escapes that single layer, the synchronous wrapper calls response_for_exception(request, exc) directly; the asynchronous wrapper calls await sync_to_async(response_for_exception, thread_sensitive=False)(request, exc).

Inside response_for_exception: six branches

response_for_exception maps Python exceptions onto HTTP status codes, security loggers, signals, and error views across six ordered isinstance branches:

  1. Http404 (404): When settings.DEBUG is True, Django returns technical_404_response listing every URL pattern tried. In production (DEBUG = False), it calls get_exception_response(request, resolver, 404, exc) to invoke handler404. Notice what it does not do here: it does not emit got_request_exception, and it does not call log_response itself — BaseHandler.get_response logs the resulting 404 response at "WARNING" on "django.request".
  2. PermissionDenied (403): Resolves handler403 and logs "Forbidden (Permission denied)" at "WARNING" on "django.request".
  3. MultiPartParserError (400): Resolves handler400 and logs "Bad request (Unable to parse request body)" on "django.request".
  4. BadRequest (400): Returns technical_500_response(..., status_code=400) when settings.DEBUG is True, or handler400 in production, logging on "django.request".
  5. SuspiciousOperation (400): Covers DisallowedHost, DisallowedRedirect, SuspiciousSession, and payload-limit subclasses (RequestDataTooBig, TooManyFieldsSent, TooManyFilesSent). On those three payload-limit subclasses, line 118 calls HttpRequest._mark_post_parse_error so that if a custom handler400 template or middleware touches WSGIRequest.POST, it gets an empty QueryDict instead of triggering the exact same exception again. Then lines 130–138 log the event at "ERROR" to a dedicated "django.security.<ClassName>" logger — never "django.request" — so security alerts stay separated from ordinary 4xx traffic.
  6. Every other Exception (500): Emits got_request_exception via Signal.send, calls handle_uncaught_exception, and logs "ERROR" to "django.request".

At the end of response_for_exception (lines 155–158), if any error view returned an unrendered TemplateResponse, Django forces SimpleTemplateResponse.render immediately inside the boundary. And inside get_exception_response (lines 163–171), if a custom handler404, handler403, or handler400 itself raises an exception, Django catches it, fires got_request_exception, and falls back to handle_uncaught_exception (500).

Watching every path live

Run all six exception categories — plus a process_exception recovery, an inner middleware crash, DEBUG_PROPAGATE_EXCEPTIONS = True, and a BaseException subclass — through our three-layer probe chain:

Recorded on Django 6.1.3 ch03-handlers script
Per-layer exception walls: convert_exception_to_response and response_for_exception
  View raises Http404 -> 404 Not Found  got_request_exception=0  loggers=[('django.request', 'WARNING')]
    trace: Outer.process_request -> Middle.process_request -> Inner.process_request -> Outer.process_view -> Middle.process_view -> Inner.process_view -> view.probe_view -> Inner.process_exception(Http404) -> Middle.process_exception(Http404) -> Outer.process_exception(Http404) -> Inner.process_response(status=404) -> Middle.process_response(status=404) -> Outer.process_response(status=404)
  View raises PermissionDenied -> 403 Forbidden  got_request_exception=0  loggers=[('django.request', 'WARNING')]
    trace: Outer.process_request -> Middle.process_request -> Inner.process_request -> Outer.process_view -> Middle.process_view -> Inner.process_view -> view.probe_view -> Inner.process_exception(PermissionDenied) -> Middle.process_exception(PermissionDenied) -> Outer.process_exception(PermissionDenied) -> Inner.process_response(status=403) -> Middle.process_response(status=403) -> Outer.process_response(status=403)
  View raises BadRequest -> 400 Bad Request  got_request_exception=0  loggers=[('django.request', 'WARNING')]
    trace: Outer.process_request -> Middle.process_request -> Inner.process_request -> Outer.process_view -> Middle.process_view -> Inner.process_view -> view.probe_view -> Inner.process_exception(BadRequest) -> Middle.process_exception(BadRequest) -> Outer.process_exception(BadRequest) -> Inner.process_response(status=400) -> Middle.process_response(status=400) -> Outer.process_response(status=400)
  View raises DisallowedHost (SuspiciousOperation) -> 400 Bad Request  got_request_exception=0  loggers=[('django.security.DisallowedHost', 'ERROR')]
    trace: Outer.process_request -> Middle.process_request -> Inner.process_request -> Outer.process_view -> Middle.process_view -> Inner.process_view -> view.probe_view -> Inner.process_exception(DisallowedHost) -> Middle.process_exception(DisallowedHost) -> Outer.process_exception(DisallowedHost) -> Inner.process_response(status=400) -> Middle.process_response(status=400) -> Outer.process_response(status=400)
  View raises RuntimeError -> 500 Internal Server Error  got_request_exception=1  loggers=[('django.request', 'ERROR')]
    trace: Outer.process_request -> Middle.process_request -> Inner.process_request -> Outer.process_view -> Middle.process_view -> Inner.process_view -> view.probe_view -> Inner.process_exception(RuntimeError) -> Middle.process_exception(RuntimeError) -> Outer.process_exception(RuntimeError) -> Inner.process_response(status=500) -> Middle.process_response(status=500) -> Outer.process_response(status=500)
  View raises RuntimeError + Middle.process_exception recovers -> 503 Service Unavailable  got_request_exception=0  loggers=[('django.request', 'ERROR')]
    trace: Outer.process_request -> Middle.process_request -> Inner.process_request -> Outer.process_view -> Middle.process_view -> Inner.process_view -> view.probe_view -> Inner.process_exception(RuntimeError) -> Middle.process_exception(RuntimeError) -> Middle.process_exception -> RECOVERED 503 -> Inner.process_response(status=503) -> Middle.process_response(status=503) -> Outer.process_response(status=503)
  Inner.process_request raises RuntimeError -> 500 Internal Server Error  got_request_exception=1  loggers=[('django.request', 'ERROR')]
    trace: Outer.process_request -> Middle.process_request -> Inner.process_request -> Middle.process_response(status=500) -> Outer.process_response(status=500)
  DEBUG_PROPAGATE_EXCEPTIONS=True -> escaped RuntimeError: database desk on fire
  CustomBaseCrash(BaseException) -> escaped uncaught: non-Exception BaseException

Three lines in that recording deserve a second look because they catch senior Django engineers off guard in production:

Where exception boundaries leak

With entry points, the onion, hooks, and exception walls in place, we can now open the most intricate machinery in Chapter 3: how Django mixes synchronous and asynchronous layers inside one request chain without deadlocking the event loop, in Sync and async inside one chain.