2016-06-14 15:41:58 +08:00
|
|
|
import logging
|
|
|
|
import sys
|
|
|
|
from functools import wraps
|
|
|
|
|
|
|
|
from django.conf import settings
|
|
|
|
from django.core import signals
|
2017-02-10 16:30:51 +08:00
|
|
|
from django.core.exceptions import (
|
2018-02-03 03:44:07 +08:00
|
|
|
PermissionDenied, RequestDataTooBig, SuspiciousOperation,
|
|
|
|
TooManyFieldsSent,
|
2017-02-10 16:30:51 +08:00
|
|
|
)
|
2016-06-14 15:41:58 +08:00
|
|
|
from django.http import Http404
|
|
|
|
from django.http.multipartparser import MultiPartParserError
|
|
|
|
from django.urls import get_resolver, get_urlconf
|
2017-07-13 12:09:18 +08:00
|
|
|
from django.utils.log import log_response
|
2016-06-14 15:41:58 +08:00
|
|
|
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.
|
|
|
|
"""
|
2017-01-22 02:20:17 +08:00
|
|
|
@wraps(get_response)
|
2016-06-14 15:41:58 +08:00
|
|
|
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):
|
2017-07-13 12:09:18 +08:00
|
|
|
response = get_exception_response(request, get_resolver(get_urlconf()), 403, exc)
|
|
|
|
log_response(
|
2016-06-14 15:41:58 +08:00
|
|
|
'Forbidden (Permission denied): %s', request.path,
|
2017-07-13 12:09:18 +08:00
|
|
|
response=response,
|
|
|
|
request=request,
|
|
|
|
exc_info=sys.exc_info(),
|
2016-06-14 15:41:58 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
elif isinstance(exc, MultiPartParserError):
|
2017-07-13 12:09:18 +08:00
|
|
|
response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc)
|
|
|
|
log_response(
|
2016-06-14 15:41:58 +08:00
|
|
|
'Bad request (Unable to parse request body): %s', request.path,
|
2017-07-13 12:09:18 +08:00
|
|
|
response=response,
|
|
|
|
request=request,
|
|
|
|
exc_info=sys.exc_info(),
|
2016-06-14 15:41:58 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
elif isinstance(exc, SuspiciousOperation):
|
2017-02-10 16:30:51 +08:00
|
|
|
if isinstance(exc, (RequestDataTooBig, TooManyFieldsSent)):
|
|
|
|
# POST data can't be accessed again, otherwise the original
|
|
|
|
# exception would be raised.
|
|
|
|
request._mark_post_parse_error()
|
|
|
|
|
2016-06-14 15:41:58 +08:00
|
|
|
# The request logger receives events for any problematic request
|
|
|
|
# The security logger receives events for all SuspiciousOperations
|
|
|
|
security_logger = logging.getLogger('django.security.%s' % exc.__class__.__name__)
|
|
|
|
security_logger.error(
|
2017-04-22 01:52:26 +08:00
|
|
|
str(exc),
|
2016-06-14 15:41:58 +08:00
|
|
|
extra={'status_code': 400, 'request': request},
|
|
|
|
)
|
|
|
|
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)
|
|
|
|
|
|
|
|
elif isinstance(exc, SystemExit):
|
|
|
|
# Allow sys.exit() to actually exit. See tickets #1023 and #4701
|
|
|
|
raise
|
|
|
|
|
|
|
|
else:
|
|
|
|
signals.got_request_exception.send(sender=None, request=request)
|
|
|
|
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
|
2017-07-13 12:09:18 +08:00
|
|
|
log_response(
|
|
|
|
'%s: %s', response.reason_phrase, request.path,
|
|
|
|
response=response,
|
|
|
|
request=request,
|
|
|
|
exc_info=sys.exc_info(),
|
|
|
|
)
|
2016-06-14 15:41:58 +08:00
|
|
|
|
2016-06-23 22:30:07 +08:00
|
|
|
# Force a TemplateResponse to be rendered.
|
|
|
|
if not getattr(response, 'is_rendered', True) and callable(getattr(response, 'render', None)):
|
|
|
|
response = response.render()
|
|
|
|
|
2016-06-14 15:41:58 +08:00
|
|
|
return response
|
|
|
|
|
|
|
|
|
|
|
|
def get_exception_response(request, resolver, status_code, exception, sender=None):
|
|
|
|
try:
|
|
|
|
callback, param_dict = resolver.resolve_error_handler(status_code)
|
2017-12-11 20:08:45 +08:00
|
|
|
response = callback(request, **{**param_dict, 'exception': exception})
|
2016-06-14 15:41:58 +08:00
|
|
|
except Exception:
|
|
|
|
signals.got_request_exception.send(sender=sender, 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, param_dict = resolver.resolve_error_handler(500)
|
|
|
|
return callback(request, **param_dict)
|