Debian Codegraph @

django/core/handlers/exception.py

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