Performance: Exception middleware
This affects server response time and user experience by handling errors during request processing.
Jump into concepts and practice - no test required
from django.http import HttpResponse import threading 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: # Quickly log error asynchronously and return response threading.Thread(target=log_error, args=(e,)).start() response = HttpResponse('Error occurred', status=500) return response def log_error(e): # Log error without blocking response pass
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 error and create response import time time.sleep(2) # Simulate slow error handling response = HttpResponse('Error occurred', status=500) return response
| Pattern | Server Blocking | Response Delay | Impact on LCP | Verdict |
|---|---|---|---|---|
| Synchronous error logging with delay | Blocks server thread | Adds 2s delay | High negative impact | [X] Bad |
| Asynchronous error logging | Non-blocking | Minimal delay | Improves LCP | [OK] Good |
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 responseclass 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 responseimport 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 response