2013-12-14 74 views
0

我有一個像這樣定義的瓶路線:瓶Pymongo異常管理

@app.route('/api/v0.1/getTopPosts', methods = ['POST']) 
@auth.login_required 
def get_top_posts(): 
    if not request.json or not 'page' in request.json: 
    abort(400) 

    resultsPerQuery = 10 
    page = int(request.json['page']) 
    skip = (page - 1) * resultsPerQuery; 

    postsToReturn = [] 
    errorDidOccur = False 

    #get top posts 
    try: 
     topPostsReturn = db.collection.find({"isActive":"yes","state":{ "$BAD" : False }}).sort('rank',1).limit(resultsPerQuery).skip(skip) 

     for topPost in topPostsReturn: 
     postsToReturn.append(db.collection.find_one({'_id':topPost['posts_id']}).copy()) 

    except pymongo.errors.OperationFailure as e: 
     errorDidOccur = True 


    if errorDidOccur: 
     reply = { 
      'reply' : 'failure', 
      'error' : e, 
      'data' : None 
     } 
    else: 
     reply = { 
      'reply' : 'success', 
      'error' : None, 
      'data' : postsToReturn 
     } 

    return dumps(reply) 

我插在$ BAD生成OperationalFailure例外。我遇到的問題是'e'不是JSON可序列化的。我得到:

TypeError: OperationFailure(u'database error: invalid operator: $BAD',) is not JSON serializable 

如何去報告錯誤回來?

感謝

回答

2

使用

'error' : e.message, 

,而不是

'error' : e,