如何返回Flask-SqlAlchemy错误详细信息

时间:2019-05-26 14:03:33

标签: flask sqlalchemy flask-sqlalchemy

我正在使用Flask 1.0Flask-SqlAlchemy 2Angular 7

当SqlAlchemy抛出错误时,我想在前端显示定制的错误消息。

official Flask documentation中有一节有关如何处理错误,还有similar question在SO中与Flask-Restless有关。但我无法将点连接起来。

当SqlAlchemy引发错误时,它看起来像这样:

DETAIL:  Key (id)=(123) is not present in table "foo".

我将错误返回到路由:

try:
    db.session.commit()
except Exception as error:
    db.session.flush()
    db.session.rollback()
    return error

在检查路线中是否有错误:

if status == True:
    return jsonify( { "success": True } ), 201
else:
    return error_response(500, str(status))

我的error_response类如下:

def error_response(status_code, message=None):
    payload = {"error": HTTP_STATUS_CODES.get(status_code, "Unknown error")}
    if message:
        payload["message"] = message
        response = jsonify(payload)
        response.status_code = status_code
    return response

但是响应json仅包含一般错误消息:

"message": "Http failure response for http://127.0.0.1:5000/database/add_foo: 0 Unknown Error"

2 个答案:

答案 0 :(得分:0)

您可以阅读error对象并从中创建自己的自定义消息。有关所有详细信息,请尝试在控制台中打印error.\__dict__

erro.__dict__

例如:

from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import Column
from sqlalchemy import Integer, String

db_uri = 'sqlite:///'
engine = create_engine(db_uri)
conn = engine.connect()

# Create a metadata instance
meta = MetaData(engine)
table = Table('user', meta,
   Column('id', Integer, primary_key=True),
   Column('l_name', String),
   Column('f_name', String))
meta.create_all()
# Insert Data
conn.execute(table.insert(),[
   {'id':1,'l_name':'Hi','f_name':'bob'},
   {'id':2,'l_name':'Hello','f_name':'john'},
   {'id':3,'l_name':'yo','f_name':'bob-john'}])

result =conn.execute("SELECT * FROM user")
for res in result:
  print(res)
# Intensionally violating unique constraint
try:
  ins = table.insert().values(
      id=3,
      l_name='Hello',
      f_name='World')
# conn = engine.connect()
  conn.execute(ins)
except Exception as error:
  print(str(error.orig) + " for parameters" + str(error.params))

输出将是:-

Custom Exception Message

答案 1 :(得分:0)

结果是我尝试进行批量保存时返回了错误:

db.session.bulk_save_objects(companies_to_add, return_defaults = True)

我的印象是,执行任一操作时都会出现错误

db.session.commit()

db.session.flush()

显然我错了。我现在将批量保存放入try块:

try:
    db.session.bulk_save_objects(companies_to_add, return_defaults = True)
except Exception as error:
    db.session.rollback()
    return error

现在我可以在前端捕获错误了。