Debian Codegraph @

docs/api-guide/exceptions.md

raw
1 ---
2 source:
3 - exceptions.py
4 ---
5
6 # Exceptions
7
8 > Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.
9 >
10 > — Doug Hellmann, [Python Exception Handling Techniques][cite]
11
12 ## Exception handling in REST framework views
13
14 REST framework's views handle various exceptions, and deal with returning appropriate error responses.
15
16 The handled exceptions are:
17
18 * Subclasses of `APIException` raised inside REST framework.
19 * Django's `Http404` exception.
20 * Django's `PermissionDenied` exception.
21
22 In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error.
23
24 Most error responses will include a key `detail` in the body of the response.
25
26 For example, the following request:
27
28 DELETE http://api.example.com/foo/bar HTTP/1.1
29 Accept: application/json
30
31 Might receive an error response indicating that the `DELETE` method is not allowed on that resource:
32
33 HTTP/1.1 405 Method Not Allowed
34 Content-Type: application/json
35 Content-Length: 42
36
37 {"detail": "Method 'DELETE' not allowed."}
38
39 Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the "non_field_errors" key, or whatever string value has been set for the `NON_FIELD_ERRORS_KEY` setting.
40
41 An example validation error might look like this:
42
43 HTTP/1.1 400 Bad Request
44 Content-Type: application/json
45 Content-Length: 94
46
47 {"amount": ["A valid integer is required."], "description": ["This field may not be blank."]}
48
49 ## Custom exception handling
50
51 You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.
52
53 The function must take a pair of arguments, the first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a `Response` object, or return `None` if the exception cannot be handled. If the handler returns `None` then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.
54
55 For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:
56
57 HTTP/1.1 405 Method Not Allowed
58 Content-Type: application/json
59 Content-Length: 62
60
61 {"status_code": 405, "detail": "Method 'DELETE' not allowed."}
62
63 In order to alter the style of the response, you could write the following custom exception handler:
64
65 from rest_framework.views import exception_handler
66
67 def custom_exception_handler(exc, context):
68 # Call REST framework's default exception handler first,
69 # to get the standard error response.
70 response = exception_handler(exc, context)
71
72 # Now add the HTTP status code to the response.
73 if response is not None:
74 response.data['status_code'] = response.status_code
75
76 return response
77
78 The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as `context['view']`.
79
80 The exception handler must also be configured in your settings, using the `EXCEPTION_HANDLER` setting key. For example:
81
82 REST_FRAMEWORK = {
83 'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
84 }
85
86 If not specified, the `'EXCEPTION_HANDLER'` setting defaults to the standard exception handler provided by REST framework:
87
88 REST_FRAMEWORK = {
89 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
90 }
91
92 Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the `HTTP_400_BAD_REQUEST` responses that are returned by the generic views when serializer validation fails.
93
94 ---
95
96 ## API Reference
97
98 ### APIException
99
100 **Signature:** `APIException()`
101
102 The **base class** for all exceptions raised inside an `APIView` class or `@api_view`.
103
104 To provide a custom exception, subclass `APIException` and set the `.status_code`, `.default_detail`, and `.default_code` attributes on the class.
105
106 For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so:
107
108 from rest_framework.exceptions import APIException
109
110 class ServiceUnavailable(APIException):
111 status_code = 503
112 default_detail = 'Service temporarily unavailable, try again later.'
113 default_code = 'service_unavailable'
114
115 #### Inspecting API exceptions
116
117 There are a number of different properties available for inspecting the status
118 of an API exception. You can use these to build custom exception handling
119 for your project.
120
121 The available attributes and methods are:
122
123 * `.detail` - Return the textual description of the error.
124 * `.get_codes()` - Return the code identifier of the error.
125 * `.get_full_details()` - Return both the textual description and the code identifier.
126
127 In most cases the error detail will be a simple item:
128
129 >>> print(exc.detail)
130 You do not have permission to perform this action.
131 >>> print(exc.get_codes())
132 permission_denied
133 >>> print(exc.get_full_details())
134 {'message':'You do not have permission to perform this action.','code':'permission_denied'}
135
136 In the case of validation errors the error detail will be either a list or
137 dictionary of items:
138
139 >>> print(exc.detail)
140 {"name":"This field is required.","age":"A valid integer is required."}
141 >>> print(exc.get_codes())
142 {"name":"required","age":"invalid"}
143 >>> print(exc.get_full_details())
144 {"name":{"message":"This field is required.","code":"required"},"age":{"message":"A valid integer is required.","code":"invalid"}}
145
146 ### ParseError
147
148 **Signature:** `ParseError(detail=None, code=None)`
149
150 Raised if the request contains malformed data when accessing `request.data`.
151
152 By default this exception results in a response with the HTTP status code "400 Bad Request".
153
154 ### AuthenticationFailed
155
156 **Signature:** `AuthenticationFailed(detail=None, code=None)`
157
158 Raised when an incoming request includes incorrect authentication.
159
160 By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
161
162 ### NotAuthenticated
163
164 **Signature:** `NotAuthenticated(detail=None, code=None)`
165
166 Raised when an unauthenticated request fails the permission checks.
167
168 By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
169
170 ### PermissionDenied
171
172 **Signature:** `PermissionDenied(detail=None, code=None)`
173
174 Raised when an authenticated request fails the permission checks.
175
176 By default this exception results in a response with the HTTP status code "403 Forbidden".
177
178 ### NotFound
179
180 **Signature:** `NotFound(detail=None, code=None)`
181
182 Raised when a resource does not exist at the given URL. This exception is equivalent to the standard `Http404` Django exception.
183
184 By default this exception results in a response with the HTTP status code "404 Not Found".
185
186 ### MethodNotAllowed
187
188 **Signature:** `MethodNotAllowed(method, detail=None, code=None)`
189
190 Raised when an incoming request occurs that does not map to a handler method on the view.
191
192 By default this exception results in a response with the HTTP status code "405 Method Not Allowed".
193
194 ### NotAcceptable
195
196 **Signature:** `NotAcceptable(detail=None, code=None)`
197
198 Raised when an incoming request occurs with an `Accept` header that cannot be satisfied by any of the available renderers.
199
200 By default this exception results in a response with the HTTP status code "406 Not Acceptable".
201
202 ### UnsupportedMediaType
203
204 **Signature:** `UnsupportedMediaType(media_type, detail=None, code=None)`
205
206 Raised if there are no parsers that can handle the content type of the request data when accessing `request.data`.
207
208 By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".
209
210 ### Throttled
211
212 **Signature:** `Throttled(wait=None, detail=None, code=None)`
213
214 Raised when an incoming request fails the throttling checks.
215
216 By default this exception results in a response with the HTTP status code "429 Too Many Requests".
217
218 ### ValidationError
219
220 **Signature:** `ValidationError(detail=None, code=None)`
221
222 The `ValidationError` exception is slightly different from the other `APIException` classes:
223
224 * The `detail` argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in the `validate()` method of a serializer. For example. `raise serializers.ValidationError({'name': 'Please enter a valid name.'})`
225 * By convention you should import the serializers module and use a fully qualified `ValidationError` style, in order to differentiate it from Django's built-in validation error. For example. `raise serializers.ValidationError('This field must be an integer value.')`
226
227 The `ValidationError` class should be used for serializer and field validation, and by validator classes. It is also raised when calling `serializer.is_valid` with the `raise_exception` keyword argument:
228
229 serializer.is_valid(raise_exception=True)
230
231 The generic views use the `raise_exception=True` flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.
232
233 By default this exception results in a response with the HTTP status code "400 Bad Request".
234
235
236 ---
237
238 ## Generic Error Views
239
240 Django REST Framework provides two error views suitable for providing generic JSON `500` Server Error and
241 `400` Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for an
242 API-only application.)
243
244 Use these as per [Django's Customizing error views documentation][django-custom-error-views].
245
246 ### `rest_framework.exceptions.server_error`
247
248 Returns a response with status code `500` and `application/json` content type.
249
250 Set as `handler500`:
251
252 handler500 = 'rest_framework.exceptions.server_error'
253
254 ### `rest_framework.exceptions.bad_request`
255
256 Returns a response with status code `400` and `application/json` content type.
257
258 Set as `handler400`:
259
260 handler400 = 'rest_framework.exceptions.bad_request'
261
262 ## Third party packages
263
264 The following third-party packages are also available.
265
266 ### DRF Standardized Errors
267
268 The [drf-standardized-errors][drf-standardized-errors] package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.
269
270 [cite]: https://doughellmann.com/blog/2009/06/19/python-exception-handling-techniques/
271 [authentication]: authentication.md
272 [django-custom-error-views]: https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views
273 [drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors