Karam Haj
Karam Haj

Reputation: 1250

Python and MongoEngine, TypeError: Object of type ValidationError is not JSON serializable

What I'm trying to is building a REST API using python tornado, all were work well until I got this message when I post data to the API "TypeError: Object of type ValidationError is not JSON serializable".

def post(self):
    try:
        data = convert_arguments(self.request.arguments)
        self.write(dict(result=HazardManager().create_hazard(**data)))
    except Exception as e:
        self.write(dict(error=e))

create_hazard() is the function that makes the connect with the database and it says to save my data and return the object

def create_hazard(self, **data):
    try:
        hazard = HazardDB(title=data['title'], datetime=data['datetime'], location=data['location'], description=data['description'])
        hazard.commit(True) 
        return hazard.to_json()
    except Exception as e:
        return e

Here how I call the POST method in my client side,

$.ajax({
    type: "POST",
    url: 'api/v1/hazards',
    data: $('form').serialize(),
    success: function(data){
        console.log(data)
    },
    error: function(){
        console.log('error')
    }
});

Upvotes: 0

Views: 970

Answers (1)

Fine
Fine

Reputation: 2154

The method self.write tries to convert your dictionary to JSON. But it fails because it can't convert ValidationError object to the JSON representation (most if not all exceptions objects couldn't be converted to JSON if it's haven't been added by a developer). Easy way to avoid that is to pass an exception message, not an exception object:

...
except Exception as e:
    self.write(dict(error=str(e)))

Upvotes: 1

Related Questions