You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/api-guide/exceptions.md
+34-9Lines changed: 34 additions & 9 deletions
Original file line number
Diff line number
Diff line change
@@ -28,28 +28,53 @@ For example, the following request:
28
28
Might receive an error response indicating that the `DELETE` method is not allowed on that resource:
29
29
30
30
HTTP/1.1 405 Method Not Allowed
31
-
Content-Type: application/json; charset=utf-8
31
+
Content-Type: application/json
32
32
Content-Length: 42
33
33
34
34
{"detail": "Method 'DELETE' not allowed."}
35
35
36
36
## Custom exception handling
37
37
38
-
To implement custom exception handling (e.g. to handle additional exception classes or to override the error response format), create an exception handler function with the following signature:
38
+
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.
39
39
40
-
exception_handler(exc)
40
+
The function must take a single argument, which is the exception to be handled, and 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.
41
41
42
-
*`exc`: The exception.
42
+
For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:
43
43
44
-
If the function returns `None`, a 500 error will be raised.
44
+
HTTP/1.1 405 Method Not Allowed
45
+
Content-Type: application/json
46
+
Content-Length: 62
47
+
48
+
{"status_code": 405, "detail": "Method 'DELETE' not allowed."}
49
+
50
+
In order to alter the style of the response, you could write the following custom exception handler:
51
+
52
+
from rest_framework.views import exception_handler
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.
0 commit comments