我有以下函数,我正在尝试处理错误,并将其发送给哨兵
import sentry_sdk
...
...
...
def create_orders(
orders: orders_schema.OrderCreate
):
try:
query = "INSERT INTO orders VALUES (nextval('orders_id_seq'), :price, :currency, :created_on, :note)"
values = {
"price": orders.price,
"currency": orders.currency,
"created_on": datetime.utcnow(),
"note": orders.note
}
except Exception as err:
sentry_sdk.capture_exception(err)
return database.execute(query, values=values)
这是调用函数的路由器端点
@router.post("/orders/create", response_model=orders_schema.OrderCreate)
async def create_new_order(
orders: orders_schema.OrderCreate
):
await crud.create_orders(orders)
return {**orders.dict()}
Sentry集成的工作原理就像我测试接收其他一些未处理的错误事件一样,但现在我想实际使用Sentry来满足我的需要;这是为了帮助管理已处理的错误
但是,当我试图向api端点发送错误的值或错误的密钥时,不会向sentine 发送任何内容
我是不是遗漏了什么,或者我该怎么做才能发送错误?
捕获sentry错误的行可能永远不会被执行,因为对DB的访问是在return语句上。。。换言之,try/except块中的内容没有失败,因此except没有运行,然后代码转到可能失败的返回行,但此时哨兵不再捕获
def create_orders(
orders: orders_schema.OrderCreate
):
try:
result = None
query = "INSERT INTO orders VALUES (nextval('orders_id_seq'), :price, :currency, :created_on, :note)"
values = {
"price": orders.price,
"currency": orders.currency,
"created_on": datetime.utcnow(),
"note": orders.note
}
result = database.execute(query, values=values)
except Exception as err:
sentry_sdk.capture_exception(err)
finally:
return result
您可以直接引发错误:
from fastapi import FastAPI, HTTPException
@router.post("/orders/create", response_model=orders_schema.OrderCreate)
async def create_new_order(orders: orders_schema.OrderCreate):
try:
await crud.create_orders(orders)
return {**orders.dict()
except Exception as e:
raise HTTPException(status_code=400,detail=e)