1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
|
import logging
import sys
from functools import wraps
from asgiref.sync import iscoroutinefunction, sync_to_async
from django.conf import settings
from django.core import signals
from django.core.exceptions import (
BadRequest,
PermissionDenied,
RequestDataTooBig,
SuspiciousOperation,
TooManyFieldsSent,
TooManyFilesSent,
)
from django.http import Http404
from django.http.multipartparser import MultiPartParserError
from django.urls import get_resolver, get_urlconf
from django.utils.log import log_response
from django.views import debug
def convert_exception_to_response(get_response):
"""
Wrap the given get_response callable in exception-to-response conversion.
All exceptions will be converted. All known 4xx exceptions (Http404,
PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
converted to the appropriate response, and all other exceptions will be
converted to 500 responses.
This decorator is automatically applied to all middleware to ensure that
no middleware leaks an exception and that the next middleware in the stack
can rely on getting a response instead of an exception.
"""
if iscoroutinefunction(get_response):
@wraps(get_response)
async def inner(request):
try:
response = await get_response(request)
except Exception as exc:
response = await sync_to_async(
response_for_exception, thread_sensitive=False
)(request, exc)
return response
return inner
else:
@wraps(get_response)
def inner(request):
try:
response = get_response(request)
except Exception as exc:
response = response_for_exception(request, exc)
return response
return inner
def response_for_exception(request, exc):
if isinstance(exc, Http404):
if settings.DEBUG:
response = debug.technical_404_response(request, exc)
else:
response = get_exception_response(
request, get_resolver(get_urlconf()), 404, exc
)
elif isinstance(exc, PermissionDenied):
response = get_exception_response(
request, get_resolver(get_urlconf()), 403, exc
)
log_response(
"Forbidden (Permission denied): %s",
request.path,
response=response,
request=request,
exception=exc,
)
elif isinstance(exc, MultiPartParserError):
response = get_exception_response(
request, get_resolver(get_urlconf()), 400, exc
)
log_response(
"Bad request (Unable to parse request body): %s",
request.path,
response=response,
request=request,
exception=exc,
)
elif isinstance(exc, BadRequest):
if settings.DEBUG:
response = debug.technical_500_response(
request, *sys.exc_info(), status_code=400
)
else:
response = get_exception_response(
request, get_resolver(get_urlconf()), 400, exc
)
log_response(
"%s: %s",
str(exc),
request.path,
response=response,
request=request,
exception=exc,
)
elif isinstance(exc, SuspiciousOperation):
if isinstance(exc, (RequestDataTooBig, TooManyFieldsSent, TooManyFilesSent)):
# POST data can't be accessed again, otherwise the original
# exception would be raised.
request._mark_post_parse_error()
if settings.DEBUG:
response = debug.technical_500_response(
request, *sys.exc_info(), status_code=400
)
else:
response = get_exception_response(
request, get_resolver(get_urlconf()), 400, exc
)
# The logger is set to django.security, which specifically captures
# SuspiciousOperation events, unlike the default django.request logger.
security_logger = logging.getLogger(f"django.security.{exc.__class__.__name__}")
log_response(
str(exc),
exception=exc,
request=request,
response=response,
level="error",
logger=security_logger,
)
else:
signals.got_request_exception.send(sender=None, request=request)
response = handle_uncaught_exception(
request, get_resolver(get_urlconf()), sys.exc_info()
)
log_response(
"%s: %s",
response.reason_phrase,
request.path,
response=response,
request=request,
exception=exc,
)
# Force a TemplateResponse to be rendered.
if not getattr(response, "is_rendered", True) and callable(
getattr(response, "render", None)
):
response = response.render()
return response
def get_exception_response(request, resolver, status_code, exception):
try:
callback = resolver.resolve_error_handler(status_code)
response = callback(request, exception=exception)
except Exception:
signals.got_request_exception.send(sender=None, request=request)
response = handle_uncaught_exception(request, resolver, sys.exc_info())
return response
def handle_uncaught_exception(request, resolver, exc_info):
"""
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses).
"""
if settings.DEBUG_PROPAGATE_EXCEPTIONS:
raise
if settings.DEBUG:
return debug.technical_500_response(request, *exc_info)
# Return an HttpResponse that displays a friendly error message.
callback = resolver.resolve_error_handler(500)
return callback(request)
|