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. 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/. 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:
Http404(404): Whensettings.DEBUGisTrue, Django returnstechnical_404_responselisting every URL pattern tried. In production (DEBUG = False), it callsget_exception_response(request, resolver, 404, exc)to invokehandler404. Notice what it does not do here: it does not emitgot_request_exception, and it does not calllog_responseitself —BaseHandlerlogs the resulting.get_response 404response at"WARNING"on"django.request".PermissionDenied(403): Resolveshandler403and logs"Forbidden (Permission denied)"at"WARNING"on"django.request".MultiPartParserError(400): Resolveshandler400and logs"Bad request (Unable to parse request body)"on"django.request".BadRequest(400): Returnstechnical_500_response(..., status_code=400)whensettings.DEBUGisTrue, orhandler400in production, logging on"django.request".SuspiciousOperation(400): CoversDisallowedHost,DisallowedRedirect,SuspiciousSession, and payload-limit subclasses (RequestDataTooBig,TooManyFieldsSent,TooManyFilesSent). On those three payload-limit subclasses, line 118 callsHttpRequestso that if a custom._mark_post_parse_error handler400template or middleware touchesWSGIRequest.POST, it gets an emptyQueryDictinstead of triggering the exact same exception again. Then lines 130–138 log the event at"ERROR"to a dedicated"djangologger — never.security.<ClassName>" "django.request"— so security alerts stay separated from ordinary 4xx traffic.- Every other
Exception(500): Emitsgot_request_exceptionviaSignal.send, callshandle_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 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:
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:
- View exceptions hit
process_exceptionfirst — evenHttp404. Look at line 1 of the trace: beforeconvert_exception_to_responseconvertsHttp404into a404response,BaseHandlerpasses it through Inner’s, Middle’s, and Outer’s._get_response process_exceptionhooks in reverse order. If Middle’sprocess_exceptionreturns a response (as in the503recovery trace), Outer’sprocess_exceptionis skipped andgot_request_exceptionnever fires (0). - Middleware exceptions NEVER call
process_exception. Compare the"Innertrace against the view crash right above it. When Inner’s.process_request raises RuntimeError" process_requestcrashes, Django has not enteredBaseHandleryet. Inner’s own._get_response convert_exception_to_responsewrapper catchesRuntimeErrorimmediately, turns it straight into a500response (got_request_exception=1), skips Inner’sprocess_responseand everyprocess_exceptionhook, and hands the500response directly to Middle’s and Outer’sprocess_response. - Two things escape the armor wall. Setting
DEBUG_PROPAGATE_EXCEPTIONS = Truemakeshandle_uncaught_exceptionexecute a bareraiseon line 180 (used bydjangoso test failures show the view’s real traceback instead of a.test .Client 500HTML page). And becauseconvert_exception_to_responsewritesexcept Exception, non-Exceptionsubclasses ofBaseException—SystemExit,KeyboardInterrupt,asyncio, or our synthetic CustomBaseCrash — punch straight through every wall uncaught..CancelledError
Where exception boundaries leak
- Wrapping the inner call in try/except in outer middleware is dead code. To intercept a view exception (like turning domain exceptions into JSON responses), implement
process_exceptionon a middleware class — or subscribe togot_request_exceptionif you only need observability. Wrappingget_responsein a try/except block will silently never trigger for view or inner-middleware errors. - Error views under ASGI run with
thread_sensitive=False. Look closely at lines 45–47 ofdjango/: the async branch ofcore/ handlers/ exception .py convert_exception_to_responsecallssync_to_async(response_for_exception, thread_sensitive=False). That means underASGIHandler, your customhandler404orhandler500executes on the event loop’s default thread pool rather than the request’s thread-sensitive worker — a subtle trap if your error view touches thread-local state or assumes it shares a thread with earlier middleware.
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.