2017-05-12 2 views
2

私はDjango RESTフレームワークで次のカスタム例外ハンドラを使用しています。Django Rest Frameworkの応答がJSONのシリアライズ可能なエラーではありません

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) 

"success":false, 
"data":{ "message" : "Validation error" } 

以下のように私は、JSONの出力をしたいしかし、私はエラーTypeError: Object of type 'ErrorMessage' is not JSON serializableを取得します。 JSONをシリアライズできないという理由で、クラスがErrorMessageという単純な理由は何ですか?どうすればこの問題を解決できますか?

+0

'ErrorMessage'オブジェクトを' response ['data'] 'に割り当てています。クラスオブジェクトは魔法のようにpython dictに変更することはできません。このリンクをチェックしてください:http://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields pythonクラスのオブジェクトをdictに変換します。 –

答えて

1

objectであるためシリアル化できません。dict,listまたは明白な値にする必要があります。

from rest_framework import serializers 

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

は次に、あなたが行うことができます:しかし、あなたは簡単に魔法のプロパティを使用して、あなたの問題を解決することができます__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) 
2

は、私はもっと一般的な方法は、エラーメッセージオブジェクトをシリアル化するシリアライザを作成することだと思う

def insta_exception_handler(exc, context): 
    ... 
    serializer = ErrorMessageSerializer(ErrorMessage("Validation error")) 
    response["data"] = serializer.data 
    ... 
関連する問題