Aug-05-2022, 07:54 PM
(This post was last modified: Aug-05-2022, 07:55 PM by saisankalpj.)
I want to handle exceptions in django.When the debug=True in django,we get a standard error page in html.But my requirement is that the error response should be in application/json.How do i do this.
I have tried the following way,but it doesnt work for 404(page not found),500(server error).For 404,500,i get standard error pages of django and not application/json
I have tried the following way,but it doesnt work for 404(page not found),500(server error).For 404,500,i get standard error pages of django and not application/json
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)
# Now add the HTTP status code to the response.
if response is not None:
response.data['status_code'] = response.status_code
response = JsonResponse(data={'message': response.data})
return (response)This is in my settings.py file REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'api.utils.exceptionhandler.custom_exception_handler',
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
