I have the following custom exception handler in Django REST framework.
class ErrorMessage:
def __init__(self, message):
self.message = message
def insta_exception_handler(exc, context):
response = {}
if isinstance(exc, ValidationError):
response['success'] = False
response['data'] = ErrorMessage("Validation error")
return Response(response)
I want a JSON output as shown below
"success":false,
"data":{ "message" : "Validation error" }
But I get the error TypeError: Object of type 'ErrorMessage' is not JSON serializable. Why is a class as simple as ErrorMessage above not JSON serializable? How can I solve this problem?
ErrorMessageobject toresponse['data']. Class objects can't magically change to python dict. Check this link : stackoverflow.com/questions/61517/… For converting python class objects to dict.