title: Django: how to override core handlers
body: <p>I have made a custom middleware and if it throws exception, it is automatically  handled by <code>BaseHandler</code> function <code>get_response</code> (django.core.handlers.base). My exception <code>ObjectDoesNotExist</code>, by default, is not handled and therefore a function <code>handle_uncaught_exception</code> takes care of it. But it considers all error as 500 Internal Server (even if it is a 400 Bad request) and returns default django error html template with 500 code. Here is my code: </p>
  
  <p>custom_middleware.py:</p>
  
  <pre><code>class CustomMiddleware(object):
  """
  custom middleware
  """
  def process_request(self, request):
      try:
          # if agent doesn't exists then return json response
          agent = Agent.objects.get(agent_token=agent_token)
      except ObjectDoesNotExist as e:
          raise Exception(exception_code=400, detail=e, response_msg="You are not an authorized agent", request= request_data)
  </code></pre>
  
  <p>This automatically is handled by BaseHandler.get_response()</p>
  
  <p>So to solve the problem what I did was inherited the BaseHandler and override get_response function adding exception handler for my error and which gives a <strong>json response</strong> rather than HTML template. </p>
  
  <p>base.py</p>
  
  <pre><code>from django.core.handlers.base import BaseHandler
  
  class ExceptionHandler(BaseHandler):
  
      def get_response(self, request):
          my code
  </code></pre>
  
  <p>But this doesn't help as it calls the base class method even after overriding. </p>
  
  <p>Here is the traceback:</p>
  
  <pre><code>  File "/webapp/apps/middleware/custom_middleware.py" in process_request
    49.  agent = Agent.objects.get(agent_token=agent_token)
  
  File "lib/python3.4/site-packages/django/db/models/manager.py" in manager_method
    122.  return getattr(self.get_queryset(), name)(*args, **kwargs)
  
  File "lib/python3.4/site-packages/django/db/models/query.py" in get
    387.  self.model._meta.object_name
  
  During handling of the above exception (Agent matching query does not exist.), another exception occurred:
  
  File "lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
    123.  response = middleware_method(request)
  
  File "webapp/apps/middleware/request_log.py" in process_request
    54.   raise Exception(exception_code=400, detail=e, response_msg="You are not an authorized agent", request= request_data)
  </code></pre>
  
  <p>Any help</p>