---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

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

```python
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`** (`django/core/handlers/exception.py:convert_exception_to_response`).

## An armor wall around every single layer

Look back at `BaseHandler.load_middleware` (`django/core/handlers/base.py: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)` (`django/core/handlers/exception.py:response_for_exception`).

## 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` (`django/views/debug.py:technical_404_response`) listing every URL pattern tried. In production (`DEBUG = False`), it calls `get_exception_response(request, resolver, 404, exc)` (`django/core/handlers/exception.py:get_exception_response`) 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` (`django/http/request.py:HttpRequest._mark_post_parse_error`) so that if a custom `handler400` template or middleware touches `WSGIRequest.POST` (`django/core/handlers/wsgi.py: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` (`django/core/signals.py:got_request_exception`) via `Signal.send` (`django/dispatch/dispatcher.py:Signal.send`), calls `handle_uncaught_exception` (`django/core/handlers/exception.py: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:

```text recording=ch03-handlers
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_exception` first — even `Http404`.** Look at line 1 of the trace: before `convert_exception_to_response` converts `Http404` into a `404` response, `BaseHandler._get_response` passes it through Inner's, Middle's, and Outer's `process_exception` hooks in reverse order. If Middle's `process_exception` returns a response (as in the `503` recovery trace), Outer's `process_exception` is skipped and `got_request_exception` never fires (`0`).
- **Middleware exceptions NEVER call `process_exception`.** Compare the `"Inner.process_request raises RuntimeError"` trace against the view crash right above it. When Inner's `process_request` crashes, Django has not entered `BaseHandler._get_response` yet. Inner's own `convert_exception_to_response` wrapper catches `RuntimeError` immediately, turns it straight into a `500` response (`got_request_exception=1`), skips Inner's `process_response` and *every* `process_exception` hook, and hands the `500` response directly to Middle's and Outer's `process_response`.
- **Two things escape the armor wall.** Setting `DEBUG_PROPAGATE_EXCEPTIONS = True` makes `handle_uncaught_exception` execute a bare `raise` on line 180 (used by `django.test.Client` so test failures show the view's real traceback instead of a `500` HTML page). And because `convert_exception_to_response` writes `except Exception`, non-`Exception` subclasses of `BaseException` — `SystemExit`, `KeyboardInterrupt`, `asyncio.CancelledError`, or our synthetic CustomBaseCrash — punch straight through every wall uncaught.

## 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_exception` on a middleware class — or subscribe to `got_request_exception` if you only need observability. Wrapping `get_response` in 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 of `django/core/handlers/exception.py`: the async branch of `convert_exception_to_response` calls `sync_to_async(response_for_exception, thread_sensitive=False)`. That means under `ASGIHandler`, your custom `handler404` or `handler500` executes 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](async-bridge.md).
