Python Forum

Full Version: exception handling
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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',
    ],
}
from django.http import Http404, HttpResponse, render
#Create Exception Middileware 
class ExceptionHandle:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)       

    def process_exception(self, request, exception):
        return render(request, exception)

MIDDLEWARE = [
    
    'config.utils.TenantMainMiddleware',
    'config.utils.TenantMiddleware',
    'config.utils.ExceptionHandle',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


#settings.py
if not DEBUG:
    MIDDLEWARE+='middleware_location.ExceptionHandle'

#My Loaction Is config/utills (Here i write Exception Middleware)
#so my middleware loaction is 'config.utills.ExceptionHandle'