Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

446
Views
Global Exception Handling in Django-rest-framework

Is there a way to handle all the exceptions globally without using try-except block in django rest framework.

I want to convert html error page that django is throwing to a customised json object response.

I have created an exception.py file in my app

def custom_exception_handler(exc, context=None):
    response = exception_handler(exc)


    if isinstance(exc, HttpResponseServerError):  
        custom_response_data = { 
            'detail': 'Internal Server Error' # custom exception message
        }
        response.data = custom_response_data

    return response

i have configured this in settings.py.

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'EXCEPTION_HANDLER':'my_project.my_app.exceptions.custom_exception_handler'}
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

The definite answer to your question is no.

At least I don't know how to do it globally in Django, whereas global includes middleware exceptions).

Further, as request by @Shubham Kumar, the hook you need is process_exception and for an implementation check this SO post with the offical docs on how to activate it. As stated in the Django docs:

request is an HttpRequest object. exception is an Exception object raised by the view function.

Django calls process_exception() when a view raises an exception. process_exception() should return either None or an HttpResponse object. If it returns an HttpResponse object, the template response and response middleware will be applied and the resulting response returned to the browser. Otherwise, default exception handling kicks in.

Again, middleware are run in reverse order during the response phase, which includes process_exception. If an exception middleware returns a response, the process_exception methods of the middleware classes above that middleware won’t be called at all.

Meaning that you will merely be able to hook into the view function and catch all those exceptions.

over 4 years ago · Santiago Trujillo Report

0

Since I came across with a similar situation that lead me to this question, I'll answer following the original question that is related to Django Rest Framework specifically and not just Django.

I understand that you want to handle raised exceptions from your views, globally, without having to define try/except blocks on each view module.

DRF allows you to define your own Custom Exception Handling mechanism (docs). Here is an example:

At my_custom_except_handler.py:

import logging
from rest_framework.views import exception_handler
from django.http import JsonResponse
from requests import ConnectionError

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first
    response = exception_handler(exc, context)

    # checks if the raised exception is of the type you want to handle
    if isinstance(exc, ConnectionError):
        # defines custom response data
        err_data = {'MSG_HEADER': 'some custom error messaging'}

        # logs detail data from the exception being handled
        logging.error(f"Original error detail and callstack: {exc}")
        # returns a JsonResponse
        return JsonResponse(err_data, safe=False, status=503)

    # returns response as handled normally by the framework
    return response

As stated in the docs, the defined response object refers to:

The exception handler function 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.

In other words, 'response' won't be None only when handling these exceptions docs:

  • Subclasses of APIException.
  • Django's Http404 exception.
  • Django's PermissionDenied exception.

If your custom handler returns None, then the exception will be handled 'normally' by the framework, returning typical 500 server error.

Finally remember to set the required key at settings.py:

REST_FRAMEWORK = {'EXCEPTION_HANDLER': 
    'my_project.my_app.my_custom_except_handler.custom_exception_handler'}

Hope it helps!

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!