@@ -28,28 +28,53 @@ For example, the following request:
Might receive an error response indicating that the `DELETE` method is not allowed on that resource:
HTTP/1.1 405 Method Not Allowed
Content-Type: application/json; charset=utf-8
Content-Type: application/json
Content-Length: 42
{"detail": "Method 'DELETE' not allowed."}
## Custom exception handling
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:
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.
exception_handler(exc)
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.
*`exc`: The exception.
For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:
If the function returns `None`, a 500 error will be raised.
HTTP/1.1 405 Method Not Allowed
Content-Type: application/json
Content-Length: 62
{"status_code": 405, "detail": "Method 'DELETE' not allowed."}
In order to alter the style of the response, you could write the following custom exception handler:
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.