2014-01-14 79 views
1

我有Python代碼以下塊交談DynamoDB在AWS:如何從AWS DynamoDB python異常中提取異常消息?

try: 
    response = conn.batch_write_item(batch_list) 
except Exception ,e: 
    try: 
     mess = e.message 
    except: 
     mess = "NOMESS" 

    try: 
     earg0 = e.args[0] 
    except: 
     earg0 = "NOEARG0" 

    try: 
     stre = str(e) 
    except: 
     stre = "NOSTRE" 

    print "mess = '%s'" % mess 
    print "earg0 = '%s'" % earg0 
    print "stre = '%s'" % stre 

我得到的是這樣的:

mess = '' 
earg0 = 'NOEARG0' 
stre = 'DynamoDBValidationError: 400 Bad Request {'message': 'Item size has exceeded the maximum allowed size', '__type': 'com.amazon.coral.validate#ValidationException'}' 

我需要從某種程度上可靠地提取message字符串,如'Item size has exceeded the maximum allowed size'e。我該怎麼做?

回答

1

我假設您使用boto來訪問DynamoDB。

這裏是__init__方法JSONResponseErrorDynamoDBValidationError的supersuperclass):

self.status = status 
self.reason = reason 
self.body = body 
if self.body: 
    self.error_message = self.body.get('message', None) 
    self.error_code = self.body.get('__type', None) 
    if self.error_code: 
     self.error_code = self.error_code.split('#')[-1] 

大膽猜測:我將與e.error_message去得到 '項目規模已突破......'。

您還可以打印的e所有屬性(和值):

for attr in dir(e): 
    print "e[%r] = '''%s'''" % (attr, getattr(e, attr)) 
0

採取e.body,你會得到錯誤的字典。

例如: {u'message ':u'The條件請求失敗',U '型__':u'com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException'}

從這個容易,你會得到消息。