What if you could catch all errors in one place and never repeat error code again?
Why Exception middleware in Django? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine building a Django app where you have to catch errors in every view manually to show friendly messages or log issues.
Manually handling exceptions in each view is repetitive, easy to forget, and leads to inconsistent error responses across your app.
Exception middleware centralizes error handling so you write the logic once, and it automatically catches and processes exceptions for all requests.
try: # view logic except Exception as e: return HttpResponse('Error occurred')
from django.http import HttpResponse class ExceptionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: response = self.get_response(request) except Exception: return HttpResponse('Error occurred') return response
This lets you keep your views clean and ensures consistent, centralized error handling across your whole Django app.
When a user visits a broken page, exception middleware can catch the error and show a nice error page instead of a confusing server error.
Manual error handling in views is repetitive and inconsistent.
Exception middleware centralizes error catching in one place.
This improves code cleanliness and user experience with consistent error responses.
Practice
Solution
Step 1: Understand middleware role
Middleware processes requests and responses in Django, and exception middleware specifically handles errors.Step 2: Identify exception middleware purpose
Its job is to catch exceptions during request handling and provide friendly error messages or logging.Final Answer:
To catch errors during request processing and handle them gracefully -> Option AQuick Check:
Exception middleware = catch errors [OK]
- Confusing middleware with static file serving
- Thinking it manages database queries
- Assuming it handles user sessions
Solution
Step 1: Recall middleware structure
Django middleware classes require an __init__ and a __call__ method to be callable.Step 2: Identify request processing method
The __call__ method is called for each request and is where exception handling happens.Final Answer:
__call__ -> Option BQuick Check:
Request processing method = __call__ [OK]
- Choosing process_exception which is for old-style middleware
- Confusing __init__ as request handler
- Inventing non-existent handle_request method
class ExceptionMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
try:
response = self.get_response(request)
except ZeroDivisionError:
return HttpResponse('Division error caught')
return responseSolution
Step 1: Analyze try-except block
The middleware calls get_response inside try; if ZeroDivisionError occurs, it returns a custom HttpResponse.Step 2: Determine output on error
When ZeroDivisionError happens, the except block returns HttpResponse('Division error caught').Final Answer:
HttpResponse with text 'Division error caught' -> Option DQuick Check:
Error caught returns custom response [OK]
- Assuming original response is returned despite error
- Expecting default 500 error page
- Thinking request will hang without response
class ExceptionMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
try:
response = self.get_response(request)
except Exception as e:
print('Error:', e)
return responseSolution
Step 1: Check exception handling flow
If an exception occurs, except block prints error but does not return a response.Step 2: Understand middleware response requirement
Middleware must always return a response; missing return in except causes NameError or no response.Final Answer:
Missing return statement inside except block -> Option CQuick Check:
Exception block must return response [OK]
- Ignoring missing return causes runtime error
- Thinking print is enough for error handling
- Confusing method names or missing __init__
import json
from django.http import HttpResponse
class ExceptionMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
try:
response = self.get_response(request)
except Exception as e:
# Log the error
print(f'Error: {e}')
# Return JSON error response
error_content = json.dumps({'error': 'Server error'})
return HttpResponse(error_content, content_type='application/json', status=500)
return responseSolution
Step 1: Check error logging
The except block prints the error, which acts as logging here.Step 2: Verify JSON response and status
It returns HttpResponse with JSON content, correct content_type, and status 500.Final Answer:
Correctly logs error and returns JSON response with status 500 -> Option AQuick Check:
Logs error + JSON 500 response [OK]
- Forgetting to set content_type to application/json
- Not returning response in except block
- Raising exception instead of handling
