1

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?

  • Can you show us any view code or pther code that is relevant? What have you tried so far and how did it fail? Was there an error? Can you post that error if there was. – Swift Oct 27 '22 at 09:23
  • https://djangosnippets.org/snippets/428/ checkout this – rahul.m Oct 27 '22 at 09:30

1 Answers1

0

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