Custom Error Handling Middleware

A snippet showing how to handle errors gracefully in middleware.


# middleware.py

import logging
from django.http import JsonResponse
from django.shortcuts import render

logger = logging.getLogger(__name__)

class ErrorHandlingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            return self.get_response(request)
        except Exception as exc:
            logger.exception("Unhandled error on %s %s", request.method, request.path)
            wants_json = request.path.startswith('/api/') or 'application/json' in request.headers.get('Accept', '')
            if wants_json:
                return JsonResponse({'detail': 'Server error'}, status=500)
            return render(request, '500.html', status=500)
  

# settings.py

MIDDLEWARE = [
    # ...
    'your_app.middleware.ErrorHandlingMiddleware',
]

# Make sure Django doesn't swallow exceptions in debug.
DEBUG = False

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {'class': 'logging.StreamHandler'},
    },
    'root': {'handlers': ['console'], 'level': 'ERROR'},
}
  

# templates/500.html

<!doctype html>
<html>
  <head><meta charset="utf-8"><title>Server Error</title></head>
  <body>
    <h1>Something went wrong</h1>
    <p>Our team has been notified. Please try again later.</p>
  </body>
</html>
  
Explanation:
  • The middleware wraps your view; any unhandled exception is logged with stack trace using logger.exception().
  • If the request targets an API (path starts with /api/ or client accepts JSON), a JSON 500 is returned; otherwise a friendly HTML page.
  • Set DEBUG = False to ensure custom error handling is used in non‑dev environments.
  • You can integrate alerts (email/Sentry) by adding a logging handler or calling your notifier inside the except block.
  • Category Middleware
  • Total Views 771
  • Last Modified 24 February, 2026
  • Tags #middleware #error handling #exceptions #logging
Previous snippet
Enforce HTTPS Middleware
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.