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
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
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.
Examples
Django
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)
Django
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)
Sample Program
This middleware catches any exception during request processing and returns a 500 response with the error message.
Django
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', # ... # ]
Important Notes
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.
Summary
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
1. What is the main purpose of exception middleware in Django?
easy
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]
Hint: Exception middleware catches errors in requests [OK]
Common Mistakes:
- Confusing middleware with static file serving
- Thinking it manages database queries
- Assuming it handles user sessions
2. Which method must be implemented in a Django exception middleware class to process requests?
easy
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]
Hint: Middleware uses __call__ to handle requests [OK]
Common Mistakes:
- Choosing process_exception which is for old-style middleware
- Confusing __init__ as request handler
- Inventing non-existent handle_request method
3. Given this middleware snippet, what will be the output if a ZeroDivisionError occurs during request processing?
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 responsemedium
Solution
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]
Hint: Exception triggers except block response [OK]
Common Mistakes:
- Assuming original response is returned despite error
- Expecting default 500 error page
- Thinking request will hang without response
4. Identify the error in this exception middleware code:
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 responsemedium
Solution
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]
Hint: Always return response in except block [OK]
Common Mistakes:
- Ignoring missing return causes runtime error
- Thinking print is enough for error handling
- Confusing method names or missing __init__
5. You want to create exception middleware that logs errors and returns a JSON error response with status 500. Which code snippet correctly implements this behavior?
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 responsehard
Solution
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]
Hint: Print error then return JSON with status 500 [OK]
Common Mistakes:
- Forgetting to set content_type to application/json
- Not returning response in except block
- Raising exception instead of handling
