Exception middleware helps catch errors in your Django app and handle them gracefully. It keeps your app from crashing and shows friendly error messages.
Exception middleware in Django
class YourExceptionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: response = self.get_response(request) return response except Exception as e: # Handle the exception here return self.handle_exception(request, e) def handle_exception(self, request, exception): # Your custom error handling logic pass
The middleware class must accept get_response in __init__.
The __call__ method processes the request and can catch exceptions.
from django.http import HttpResponse class SimpleExceptionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: return self.get_response(request) except Exception: return HttpResponse('Something went wrong!', status=500)
from django.http import HttpResponse import logging class LoggingExceptionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: return self.get_response(request) except Exception as e: logging.error(f'Error: {e}') return HttpResponse('Internal server error', status=500)
This middleware catches any exception during request processing and returns a 500 response with the error message.
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) return response except Exception as e: return self.handle_exception(request, e) def handle_exception(self, request, exception): return HttpResponse(f'Error caught: {exception}', status=500) # Usage in settings.py: # MIDDLEWARE = [ # 'yourapp.middleware.ExceptionMiddleware', # ... # ]
Always add your middleware class to the MIDDLEWARE list in settings.py.
Be careful not to hide useful error details during development; use custom error pages mainly in production.
You can customize handle_exception to log errors or send alerts.
Exception middleware catches errors during request handling.
It helps show friendly error messages or log problems.
Write a class with __init__ and __call__ methods to create it.
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
Ready to prove it?
Pass the test and this pattern moves unknown
