StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 13 · Middleware

Exception Capture Ordering

mediumDjango MiddlewareError Handling—No data yet

Problem statement

In this Django project, implement the request-id layer that makes a failure traceable. The report exporter is half-written and raises on every call, so the page answers with a raw 500 that ties to nothing, and support has no way to say which request broke. Build a middleware in app/middleware.py that mints an id when a request arrives, carries it out on every response, and turns an unhandled view error into a defined JSON answer, then register it where it can reach the traffic a short-circuiting layer would otherwise hide from it.

Requirements

Implement:

  • a request-id and error-capture middleware in app/middleware.py
  • its entry in the MIDDLEWARE list in project/settings.py

The following files are already implemented and provided: app/views.py, app/urls.py and app/given_middleware.py. There is no model and no form in this question. The routes are given: / (home) prints a banner, /reports/ (report-index) answers 200 and sets its own X-Report-Version: 2 header, /reports/export/ (report-export) is the half-written exporter and raises on every call, and /reports/<pk>/ (report-detail) answers 200 for ids 1 and 2 and raises Http404 for anything else. Two layers in _app/given_middleware.py_ are given and neither is graded: RequestTimingMiddleware logs method, path, status and duration, and reads request.request_id on the way back out, after everything below it has run, logging - when nothing put one there; MaintenanceModeMiddleware answers every request with 503 while MAINTENANCE_MODE is on, without calling anything below it, and the setting ships off while the tests turn it on themselves. Both are deliberate stand-ins cut down to the one thing this question needs, so neither is a model answer: the gate has no staff exemption, no allowlist and no Retry-After header, and the timing layer writes its values as prose in milliseconds rather than as named fields.

1. The id, minted per request

  • Every request carries its own id, minted when the request arrives. Its shape is yours - uuid.uuid4().hex, a hex token, your own scheme - and the only demands are that it is non-empty, that it is one value for the whole of one request, and that two requests never share one.
  • A value computed once at import time is one trace id shared by every visitor for the life of the process, and three requests in one session must report three different ids.

2. The id on the way out

  • Every response leaves with the header X-Request-Id carrying that request's id: the failing responses and the ordinary pages alike.

3. The error response

  • An unhandled exception raised by a view answers 500 with content type application/json and a body carrying detail of Server error and request_id of that request's id: ``json {"detail": "Server error", "request_id": "8f14e45fceea167a5a36dedd4bea2543"} ``
  • The id in the body and the id in the X-Request-Id header of that same response are the same value.
  • Django wraps every layer in convert_exception_to_response, so a layer's get_response call hands back a 500 response rather than raising, and a try/except around it never catches anything. The hook Django calls for what a view raised is process_exception, consulted from the bottom of the stack up, taking the first response that is not None.

4. What the layer leaves alone

  • A view that raises Http404 keeps answering 404, and that answer does not carry the server-error body. Http404 reaches the same hook, and it already has the right answer, so the exceptions that are not yours are declined rather than converted.
  • A response that worked keeps its status, its body, its content type and the headers the view set. X-Request-Id is the only thing the layer adds to it.

5. The position in MIDDLEWARE

  • The layer is registered above the given MaintenanceModeMiddleware. The gate answers without calling anything below it, so a layer listed under it never runs for a gated request and the 503 leaves with no id on it.
  • That is asserted both ways: with MAINTENANCE_MODE on the gate's 503 carries X-Request-Id, and the tests then run the same entries a second time with yours moved to the bottom of the list and require the header to be missing.
  • Where the layer sits relative to the given timing layer is a free choice. That one reads the id on the way out, after everything below it has already run, so the log line carries the id whether your layer is above it or below it.

Notes

  • Only app/middleware.py and the MIDDLEWARE list in project/settings.py change; leave the rest of the settings file alone.
  • Do not edit the view and do not make the exporter stop raising. The error is converted, not removed.
  • Do not touch the given layers in _app/given_middleware.py_, and do not re-implement what they do.
  • JsonResponse serialises a dict and sets the JSON content type for you.
  • No third-party packages: uuid, secrets and django.http are all this needs.

More in Middleware

See the module
Request Timing MiddlewareNothing in the project records what each request asked for or how long it took, so operations has no timing or identity in the logs. Write the middleware that times the downstream handling and logs one structured entry per request while passing every response through untouched.—No data yetmediumMaintenance Mode GateDuring releases the site should return a maintenance response, except for staff who need to verify the deploy. Write the middleware that short-circuits with the defined 503 before the view runs, exempting staff users and the allowlisted paths.—No data yetmediumObservable Request PipelineThe app needs one coherent request pipeline - identity, timing, maintenance gating, and error conversion working together in the right order - and currently has none of it. Write the layers that assign a request id, log one timed entry carrying it, gate general traffic with the defined 503 while staff pass, and convert an unhandled view exception into the defined error response, then register them so every concern sees what it must.0%0 of 1 solvedmedium

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.