To do that, you can implement a custom exception handler function that returns the custom response in case of a Throttled
exceptions.
from rest_framework.views import exception_handler
from rest_framework.exceptions import Throttled
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
if isinstance(exc, Throttled): # check that a Throttled exception is raised
custom_response_data = { # prepare custom response data
'message': 'request limit exceeded',
'availableIn': '%d seconds'%exc.wait
}
response.data = custom_response_data # set the custom response data on response object
return response
Then, you need to add this custom exception handler to your DRF settings.
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
I think it would be slightly difficult to know the throttleType
without changing some DRF code as DRF raises a Throttled
exception in case of any the Throttle classes throttling a request. No information is passed to the Throttled
exception about which throttle_class
is raising that exception.