7

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?

1
  • You are assigning ErrorMessage object to response['data']. Class objects can't magically change to python dict. Check this link : stackoverflow.com/questions/61517/… For converting python class objects to dict. Commented May 12, 2017 at 7:42

2 Answers 2

6

It is not serializable because it is an object, it should be dict, list or plain value. But you can easily fix your problem by using magic property __dict__

def insta_exception_handler(exc, context):
    response = {}

    if isinstance(exc, ValidationError):
        response['success'] = False
        # like this
        response['data'] = ErrorMessage("Validation error").__dict__

    return Response(response)
Sign up to request clarification or add additional context in comments.

Comments

6

I think more generic way would be to create a serializer for serializing the error message object:

from rest_framework import serializers

class ErrorMessageSerializer(serializers.Serializer):
    message = serializers.CharField(max_length=256)

Then you can do:

def insta_exception_handler(exc, context):
    ...
    serializer = ErrorMessageSerializer(ErrorMessage("Validation error"))
    response["data"] = serializer.data
    ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.