Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
exception handling
#1
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',
    ],
}
Reply
#2
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'
Larz60+ write Aug-09-2022, 10:21 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use bbcode tags on future posts.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020