djangodjango-middlewaredjango-errors

Django: HTTPResponse to JSONResponse with Traceback


I am working on a middleware where i need to convert the HTTPResponse(ex: 500 internal error) to a JSONResponse like below

{
"error":"some error string",
"traceback":"complete traceback of exception"
}

Can someone please guide me how i can achieve this?


Solution

  • We can use the EXCEPTION_HANDLER in REST for this job.

    
    REST_FRAMEWORK = 
      {
        'EXCEPTION_HANDLER': 'core.middlewares.custom_exception_handler'
      }
    
    
    def custom_exception_handler(exc, context):
        response = exception_handler(exc, context)
        if not response:
            response_data = dict()
            exc_tb = tb.format_exc()
            response_data['status'] = 'failed'
            response_data['code'] = 500
            response_data['errors'] = [{'server_error': str(exc)}]
            response_data['traceback'] = exc_tb
            return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR, data=response_data)
        return response