简体   繁体   English

Flask Pymongo异常管理

[英]Flask Pymongo exception management

I have a Flask route defined like so: 我有一个像这样定义的Flask路线:

@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)

I inserted the $BAD to generate an OperationalFailure exception. 我插入$ BAD以生成OperationalFailure异常。 The problem I have is that 'e' is not JSON serializable. 我遇到的问题是'e'不是JSON可序列化的。 I get: 我明白了:

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

How do I go about reporting the error back? 如何报告错误?

Thanks 谢谢

Use 采用

'error' : e.message,

instead of 代替

'error' : e,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM