Psycopg2没有引发任何结果来获取错误

时间:2018-03-27 09:42:15

标签: python json pyramid psycopg2

我有以下代码:

def execute_statement(stmt):
    #create connection
    conn = psdb.connect(dbname='db', user='user', host='localhost', password='password')
    cur = conn.cursor()
    cur.execute(stmt)
    rows=cur.fetchall()[0]
    conn.close()
    return rows

def get_product_details(request):
     """Retrieve all information for a certain product, -> returns id, name, description and price"""

     #initiate faultstring
     faultstring = None

     #get product information from db
     try:
        row = execute_statement("""SELECT array_to_json(array_agg(pr)) FROM (SELECT id, name, description, price FROM product WHERE product.id = %(product_id)s) pr""" % request.matchdict)[0]
     except Exception as e:
         faultstring = str(e)

     #create responseobject
     resp = {}
     if faultstring:
         resp['faultstring'] = faultstring
     else:
         resp['product'] = row

     respjson = json.dumps(resp)
     return Response(json_body=json.loads(respjson))

路线:

 #get_product_details
 config.add_route('getproductdetail', '/getproductdetail/{product_id}')
 config.add_view(get_product_details, route_name='getproductdetail', renderer='json')

get_product_details()中的try / except块如果我将一个字母填入ID(例如:localhost/get_product_details/q

,则返回一个faulttring

如果我尝试获取不存在的产品,例如localhost/get_product_details/500它不会填充faulttring,并在错误确实存在时返回'products': null。为什么它不像处理错误的数据类型那样处理空提取的异常?

0 个答案:

没有答案