Exception middleware helps catch errors in your Django app and handle them gracefully. It keeps your app from crashing and shows friendly error messages.
0
0
Exception middleware in Django
Introduction
You want to log errors automatically when something goes wrong.
You want to show custom error pages instead of default ones.
You want to send notifications when exceptions happen.
You want to clean up resources or do special actions after an error.
You want to handle specific errors differently in one place.
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
This middleware catches any exception and returns a simple error message.
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)
This middleware logs the error before returning a 500 response.
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', # ... # ]
OutputSuccess
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.