私は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
という単純な理由は何ですか?どうすればこの問題を解決できますか?
'ErrorMessage'オブジェクトを' response ['data'] 'に割り当てています。クラスオブジェクトは魔法のようにpython dictに変更することはできません。このリンクをチェックしてください:http://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields pythonクラスのオブジェクトをdictに変換します。 –