How to validate the json format of request in django middleware?

I am creating a new middleware in django. In that I am checking the input in request_body. For that I need to check if the request body is json or not. But while raising exception like malformed request or bad request data I am getting 500 server error. How to handle this?

def validate_json(request):
   try:
      req_data = json.loads(request)
   except: 
      raise api_exception.BadRequest()

json_body = validate_json(request)

You can refer to above psuedo code. I want bad rrequest data 400 as response but getting 500 server error.

Back to Top